Django model inheritance: ForeignKey on parent, no related_name access to child model

4.1k Views Asked by At

Example situation as follows:

# 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

I would like to access all the related B Objects via the parent class A foreign key but I can't seem to do this. And if I access them via A then I just get the generic parent class query set. Thank you.

1

There are 1 best solutions below

0
On BEST ANSWER

When you inherit from a concrete model, there will be two tables (unlike inheriting from an abstract model) for Parent and Child models.

Django will implicitly create a OneToOneField from Child to Parent model named parent_ptr, thus:

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

will give you the desired QuerySet.