I am building a simple images blog app, And I build two models and one with Parent ForeignKey
.
I made the serializer
but when I try to create a new instance then it is keep showing me
Direct assignment to the reverse side of a related set is prohibited. Use images.set() instead.
models.py
class Gallery(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
class Image(models.Model):
gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name="images")
text = models.CharField(max_length=300)
serializer.py
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = "__all__"
class GallerySerializer(serializers.ModelSerializer):
images = ImageSerializer(many=True)
class Meta:
model = Gallery
fields = "__all__"
def create(self, validated_data):
return Gallery.objects.create(**validated_data)
Then I also tried creating both model's instances separately.
def create(self, validated_data):
new_data = Gallery.objects.create(poll=1, images=validated_data["images"])
return new_data
But it also showed me the same error it showed me before.
One more thing, validated_data
is not showing id when I use print
I am new in Django-Rest-Framework
, I have tried many times but it is still not creating.