Home > other >  drf create manytomany fields
drf create manytomany fields

Time:10-17

enter image description heremodels

    class CreatorRawArtwork(models.Model):
        id         = models.AutoField(primary_key=True)
        title      = models.CharField(max_length=500)
        descripton = models.TextField()
        editions   = models.IntegerField(null=True, blank=True)
        price      = models.CharField(max_length=500)
        created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
        medias     = models.FileField(null=True, blank=True, upload_to="raw-medias")
        user       = models.ForeignKey(
            to=Login, on_delete=models.CASCADE, related_name="creatorrawartwork",
            null=True, blank=True
        )
        collection = models.ForeignKey(
            to=DesignerCollection, on_delete=models.CASCADE, related_name="creatorrawartwork",
            null=True, blank=True
        )
        categories = models.ManyToManyField(DesignerCategories, related_name='creatorrawartwork')

        def __str__(self):
            return self.title

serializer

    class CreatorRawArtworkSerializer(serializers.ModelSerializer):
        categories = serializers.PrimaryKeyRelatedField(queryset=DesignerCategories.objects.all(), many=True)

        class Meta:
            model = CreatorRawArtwork
            fields = "__all__"
            depth=1

views

    class CreatorRawArtworkView(viewsets.ModelViewSet):
        queryset = CreatorRawArtwork.objects.all()
        serializer_class = CreatorRawArtworkSerializer

Here i am trying to create manytomany fields using drf serialier it is showing some error plese check the screenshot for parameter and responses

What can be the issue please take a look

CodePudding user response:

class CreatorRawArtworkSerializer(serializers.ModelSerializer):
        collection = DesignerCollectionSerializer(read_only=True) #assuming you have already defined serializer for *DesignerCollectionSerializer*
        categories = DesignerCategoriesSerializer(many=True)

        class Meta:
            model = CreatorRawArtwork
            fields = "__all__"
            depth=1

CodePudding user response:

enter image description here

I tested with your code and your code is working fine just make sure your request data is json

  • Related