[Answered ]-Django – Foreign key from abstract base class

2πŸ‘

SO, do you mean that you have instance of Group model and you want to have related queryset to UserConstraint or to ProjectConstraint?

There is solution to achieve this with appropriate related_name parameter in ForeignKey field. Details are available in docs.

I think you should define Constraint model like this:

class Constraint(models.Model):
    group = models.ForeignKey(Group, related_name="%(class)s_set")

    def get_constraint_type(self):
        return 'Base'

    class Meta:
        abstract = True

and use it like this:

user_constraints = group.userconstraint_set.all()
project_constraints = group.projectconstraint_set.all()

Edit:

I have changed the related_name from "%(class)s" to "%(class)s_set". The previous value was not working and I don’t know why.

Leave a comment