django - 如何从 ManyToOneRel 对象中获取相关的模型类名称?
问题描述
我有一个如下的类结构:
class Parent(models.Model):
some_fields = ...
def get_related_child_file_models_info(self):
"""
This return a generator containing all the related file model
info for each child
"""
links = (
[f.name, f]
for f in self._meta.get_fields()
if (f.one_to_many or f.one_to_one)
and f.auto_created
and not f.concrete
and "files" in f.name
)
return links
class ChildFileA(models.Model):
...
parent = models.ForeignKey(
on_delete=models.CASCADE,
related_name="child_a_files"
)
file = models.FileField()
...
class ChildFileB(models.Model):
...
parent = models.ForeignKey(
on_delete=models.CASCADE,
related_name="child_b_files"
)
file = models.FileField()
...
如果我在 for 循环中使用这个生成器,我会得到
['child_a_files', <ManyToOneRel: app_name.childfilea>]
和
['child_b_files', <ManyToOneRel: app_name.childfileb>]
目标是处理复杂的文件上传过程,我有大约 30 个不同的模型来为每个父母存储一些文件。
我尽量避免为每个人手动创建代码。
如何获取类名 和ChildFileA
对象 ?ChildFileB
ManyToOneRel
解决方案
您可以使用.field.model
. 例如:
def get_related_child_file_models_info(self):
return [
(f.name, f.field.model)
for f in self._meta.get_fields()
if (f.one_to_many or f.one_to_one)
and f.auto_created and not f.concrete
and "files" in f.name
]
这将返回对该模型类的引用。所以这里它会引用ChildFileA
and ChildFileB
。您可以访问该类的.__name__
属性以获取类名,例如:
def get_related_child_file_models_info(self):
return [
(f.name, f.field.model.__name__)
for f in self._meta.get_fields()
if (f.one_to_many or f.one_to_one)
and f.auto_created and not f.concrete
and "files" in f.name
]
推荐阅读
- php - Laravel 6 多重身份验证(登录表单)
- dialogflow-es - 使用 Action Builder 将 Google Assistant 集成到 Facebook Messenger
- ios - SwiftUI DocumentGroup 和切换到后台
- clickhouse - 在 ReplaceingMergeTree 中首选最旧版本
- r - 在 R 中绘制 nls 模型的导数
- spring-boot - Spring Boot 不映射 JSP 页面 Intellj
- java - 由于 SocketTimeoutException,如何增加 apache SSHD 的 scpClient 的 ChannelOutputStream 的等待超时?
- java - 在将统一更新到 2020 并将 jdk 更改回 1.8.0_271 后,Unity 无法构建出现错误的 android .. 请帮助我绝望:(
- c++ - 覆盖模板结构的 << 运算符
- c# - 在 winforms 中显示始终处于活动状态的表单