查找将模型连接到“直通”模型的字段

时间:2018-09-14 14:32:40

标签: python django python-2.7 django-models django-1.8

假设我的模型定义为:

# 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中的所有对象。我知道我可以通过(details here)来做到这一点:

# 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)。

1 个答案:

答案 0 :(得分:0)

在讨论here之后,在@schwobaseggl之后出现的想法在评论部分问了我一个问题,我决定使用onCreate属性使我的生活更轻松。尽管我无法获得该字段的确切名称,但是我可以在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() 来获取相关的AandB模型,也可以像上面一样命名该关系。这对我来说很有意义。我希望这也会对其他人有所帮助。

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