0

This is Django ORM models

class A(models.Model):
    ...

class B(models.Model):
    a = models.Foreignkey(A, on_delete=models.CASCADE)

class C(models.Model):
    a = models.Foreignkey(A, on_delete=models.CASCADE)

And here are the serializers:

class ASerializer(serializers.ModelSerializer):
    class Meta:
        model = A

class BSerializer(serializers.ModelSerializer):
    a = ASerializer(many=False)
    class Meta:
        model = B

class CSerializer(serializers.ModelSerializer):
    a = ASerializer(many=False)
    class Meta:
        model = C

B and C are working as expected.

Problem 1:

Now, if I want to get data of B and C from serializer A by doing b = BSerializer(many=False) and c = CSerializer(many=False). I will get an error that NameError: name 'BSerializer' is not defined and if I put B and C serializer above A errors for Aserializer. How do I fix this?

Problem 2:

B and C have one-to-one relation with A. So, when serializing A, it might not have a subsequent B or C or both data in B and C tables. So, in ASerializer

b = BSerializer(many=False)
c = CSerializer(many=False)

might give errors if there is no relation between A and C for a particular row. How do I fix this?

Amit Tripathi
  • 7,003
  • 6
  • 32
  • 58

1 Answers1

0

First, I would suggest that if you are intending to have a one-to-one relationship, that you actually define it that way:

class A(models.Model):
    ...

class B(models.Model):
    a = models.OneToOneField(A, on_delete=models.CASCADE)

class C(models.Model):
    a = models.OneToOneField(A, on_delete=models.CASCADE)

PROBLEM ONE

I have not tested this yet, but could it be a definitional order issue? What happens if you place the definition of class A after class B and class C?

PROBLEM TWO

Try adding required=False, allow_null=True as suggested here.

b = BSerializer(many=False, required=False, allow_null=True)
c = CSerializer(many=False, required=False, allow_null=True)
Community
  • 1
  • 1
Adam Hopkins
  • 6,837
  • 6
  • 32
  • 52
  • Adding definition of A after B and C would still give the error because B and C are using A. – Amit Tripathi Oct 13 '16 at 04:36
  • Hmm, well you could try something real hacky, by adding another serializer class at the end that just subclasses A: `class HackyClassA(A): pass` – Adam Hopkins Oct 13 '16 at 06:10