【发布时间】:2019-02-19 09:24:06
【问题描述】:
假设我将模型定义为:
# 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)。
【问题讨论】:
-
这不是
field.get_accessor_name()返回的值吗? -
@schwobaseggl 我想要的字段名称是
m2mfield。field.get_accessor_name()给我的是AandB_set。 -
也许可以试试
field.attname。 -
@schwobaseggl
AttributeError: 'ManyToOneRel' object has no attribute 'attname'.
标签: python django python-2.7 django-models django-1.8