【问题标题】:Find the field that connects a model to a "through" model查找将模型连接到“直通”模型的字段
【发布时间】: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 我想要的字段名称是m2mfieldfield.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


【解决方案1】:

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 模型,还可以像上面那样命名关系。这对我来说很有意义。我希望这对其他人也有帮助。

同时,如果大家有任何其他建议,请随时留下cmets或回答!

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多