1

I'm trying to achieve the following model structure:

class X(models.Model):
    class Meta:
        abstract = True

    objects  = InheritanceManager()
    agroup   = models.ForeignKey(A, related_name="%(class)s_set")
    xfield   = models.CharField()

class A(models.Model):

class Y(X):
    yfield   = models.CharField()

class Z(X):
    zfield   = models.CharField()

The first issue is, the Base X class can't be abstract it seems because I need to be able to iterate over all subclasses of X (Y,Y,Y,Z,Z) so I need access to the manager. While X is abstract, X.objects doesn't work.

Second issue is in the REST serializer. I can only reference x_set in ASerializer, as it is the only property that exists on A. And that only display the xfield in the nested list. What I would really like is y_set and z_set on the ASerializer with their respective yfield and zfield displayed.

I can achieve some of this with different configurations (iteration over children by removing abstract, or separation of children in the rest serializer by places the FK field on Y and Z directly), but never all the same time.

Thank you.

1

1 Answer 1

1

Phew!

I stuck with X being abstract, the way to then iterate over X's children:

for x_child_class in X.__subclasses__():
    for child in x_child_class.objects.all():
        #Do your stuff

And as long as X is abstract, Class A should have y_set and z_set on it, so you can just:

class ASerializer(serializers.HyperlinkedModelSerializer):
    y_set = YSerializer(many=True)
    z_set = ZSerializer(many=True)

    class Meta:
        model = A

Trivial, but took a long time for some reason.


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.