Go – Filtering models with inheritance in Django

djangodjango-models

I have two Django model classes that are structured similar to the following:

class Build(models.Model):
    project = models.CharField(max_length=100)
    ...

class CustomBuild(Build):
    custom_type = ...
    ...

I want to select all Builds and CustomBuilds (each CustomBuild has a one-to-one relationship with a Build) from the database with a specific project attribute.

I believe Build.objects.filter(project="myproject") will select the correct objects but many of them will be missing the additional data (such as custom_type) that would be provided by a CustomBuild object. On the other hand, filtering CustomBuild.objects will exclude those objects that are not CustomBuilds.

How can I accomplish this? Thanks.

Best Answer

You can fetch Build objects with Build.objects.filter() and access the subclass when you need to:

qs = Build.objects.all()
build_obj = qs[4]
custom_build_obj = build_obj.custom_build
custom_build_obj.custom_type = ...