0

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.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
MyPan
  • 3
  • 3

1 Answers1

1

The error tells you exactly what to do. Assuming validated_data['images'] is an iterable of Image objects:

def create(self, validated_data):
    new_data = Gallery.objects.create(poll=1)
    new_data.images.set(validated_data['images'])
    return new_data
Sergio
  • 21
  • 2
  • It is showing `'Image' instance expected, got OrderedDict([('text', 'First Choice'), ('gallery', )])` now – MyPan May 20 '22 at 18:55
  • When I print `validated_data['images']` then it is showing `[OrderedDict([('text', 'First Image'), ('gallery', )]), OrderedDict([('text', 'Second Image'), ('gallery', )]), OrderedDict([('text', 'Third Image'), ('gallery', )]), OrderedDict([('text', 'Fourth Image'), ('gallery', )])]` – MyPan May 20 '22 at 18:59
  • `new_data.images.set` takes an iterable of `Image` objects, but `validated_data['images']` is a `list` of `OrderedDict` objects. You will either need to retrieve the `Image` object you need via the ORM. – Sergio May 24 '22 at 18:21