首页 > 解决方案 > 查找将模型连接到“直通”模型的字段

问题描述

可以说我的模型定义为:

# The class that I will have the instance of.
class A(models.Model):
    somefieldA = models.TextField()
    m2mfield = models.ManyToManyField(B, through='AandB')

    def __unicode__(self):
        return self.somefieldA


# The model that participates in the m2m field.
class B(models.Model):
    somefieldB = models.TextField()

    def __unicode__(self):
        return self.somefieldB


# Model that stores the extra information
# about the m2m rel.
class AandB(models.Model):
    a = models.ForeignKey(A)
    b = models.ForeignKey(B)
    field1 = models.DecimalField()
    field2 = models.TextField()
    field3 = models.DateField()

我的要求是遍历模型中的所有对象AandB。我知道我可以通过(这里有详细信息)来做到这一点:

# I have the instance of model A
for field in instance._meta.get_fields(include_hidden=True):
    if field.one_to_many:
        mgr = getattr(instance, field.get_accessor_name())
        for obj in mgr.all():
            # Do stuff here.

我的问题是,有什么方法可以通过AandB模型链接到模型来获取字段名称A?(在这种情况下是m2mfield)。

标签: pythondjangopython-2.7django-modelsdjango-1.8

解决方案


在这里的讨论之后,以及@schwobaseggl 在评论部分问我一个问题后突然出现的想法,我决定使用该related_name属性来让我的生活更轻松。虽然我无法获得该字段的确切名称,但我可以通过我喜欢的任何名称related_name最终得出我最初想要的结论。

# Model that stores the extra information
# about the m2m rel.
class AandB(models.Model):
    a = models.ForeignKey(A, related_name='name_I_like_here')
    b = models.ForeignKey(B)
    field1 = models.DecimalField()
    field2 = models.TextField()
    field3 = models.DateField()

然后,我可以get_accessor_field()用来获取相关的 AandB 模型,还可以像上面那样命名关系。这对我来说很有意义。我希望这也对其他人有所帮助。

同时,如果有人有任何其他建议,请随时发表评论或回答!


推荐阅读