首页 > 解决方案 > 如何从 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

标签: djangodjango-models

解决方案


您可以使用.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
    ]

这将返回对该模型类的引用。所以这里它会引用ChildFileAand 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
    ]

推荐阅读