【问题标题】:Django model inheritance: ForeignKey on parent, no related_name access to child modelDjango模型继承:父模型上的ForeignKey,子模型没有related_name访问
【发布时间】:2017-01-14 18:33:19
【问题描述】:

示例情况如下:

# models.py
class Form(models.Model):
    name = models.CharField()

class A(models.Model):
    form = models.ForeignKey(Form)

class B(A):
    name = models.CharField()

# view.py
form = Form.objects.get(id=1)
form.a_set.all()  # works
form.b_set.all()  # doesn't work

我想通过父类A 外键访问所有相关的B 对象,但我似乎无法做到这一点。如果我通过A 访问它们,那么我只会得到通用父类查询集。谢谢。

【问题讨论】:

    标签: python django django-models django-inheritance


    【解决方案1】:

    当您从具体模型继承时,Parent 和 Child 模型将有两个表(与从抽象模型继承不同)。

    Django 将隐式创建一个从Child 到Parent 的OneToOneField 模型,命名为parent_ptr,因此:

    B.objects.filter(a_ptr__form=form)
    # B.objects.filter(a_ptr__form_id=1)
    

    会给你想要的QuerySet。

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 2011-01-13
      • 1970-01-01
      • 2019-04-15
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      相关资源
      最近更新 更多