可以说我的模型定义为:
# 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
)。
在讨论了here之后,以及在@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模型,并像上面所做的那样命名关系。这对我来说很有意义。我希望这也有助于其他人。
同时,如果有人有任何其他建议,请随时留下评论或答案!