0

I want to post a data in a serializer, having 2 ForeignKey.
I have these models:

class Child(models.Model):
    first_name = models.CharField(max_length=40)
    description = models.CharField(max_length=40)

class Parent(models.Model):
    name = models.CharField(max_length=20)
    pet = models.ForeignKey(pet)
    child = models.ForeignKey(Child, related_name='boys')

class Pet(models.Model):
    kind = models.CharField(max_length=40)
------------------,
Class PetSerializer(ModelSerializer):
    class Meta:
        model = Pet
        fields = ('kind',)

class ParentSerializer(ModelSerializer):    
    pet = PetSerializer(many=True): 
    class Meta:
        model = Parent
        fields = ('name', 'pet')

class ChildSerializer(ModelSerializer):
    boys = ParentSerializer() 

    class Meta:
        model = Child
        fields = ('first_name', 'boys')

My first question: Is it possible to get the output as:

{
    "first_name": "Peter",
    "boys": [
      {
        "name": "Bill",
         "kind": "dog"
        }
      ]
   }

My second question:And I am trying to send data to create a new model, by using this method:




    def create(self, validated_data):
        clean_data = validated_data.pop('boys')
        child = Child.objects.create(**validated_data)
        for data in clean_data:
            Parent.objects.create(child=child, **data)
        return child
But I got this error: TypeError: Direct assignment to the reverse side of a related set is prohibited. Use boys.set() instead.
4
  • is boys is foreign key of Child model? Commented Oct 18, 2019 at 12:58
  • boys is The related_name :attribute specifies the name of the reverse relation from the Child model back to Parent model.
    – Wave1988
    Commented Oct 18, 2019 at 13:04
  • For your second question, please provide your validated_data and check your code about tracks_data varibale. Also where is the username in the error. Please make your second question more clear.
    – Fogmoon
    Commented Oct 18, 2019 at 14:42
  • Sorry. It was boys.set()
    – Wave1988
    Commented Oct 19, 2019 at 6:46

1 Answer 1

1

Just for your first question, you can use source parameter in your ParentSerializer class:

class ParentSerializer(ModelSerializer):    
    kind = serializers.CharField(source='pet.kind'): 
    class Meta:
        model = Parent
        fields = ('name', 'kind')

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.