Home > Back-end >  Django Rest Framework | How to create a new product with Category name not ID
Django Rest Framework | How to create a new product with Category name not ID

Time:10-15

I have two models created in Django. I am trying to send post request from react frontend using axios API call.

My react is working fine and I can post request using category id but not with category name ( either hardcoded or from the dropdown list)

I tried using Postman, I get the same result.

class Category(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField(unique=True, null=True, blank=True)
    
    def save(self,*args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)

    def __str__(self):
        return self.name


class Product(models.Model):
    upc = models.CharField(max_length=30)
    name = models.CharField(max_length=100)
    description = models.TextField(max_length=255)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
    quantity = models.IntegerField()
    price = models.IntegerField()

    def __str__(self):
        return self.name

views.py

from .models import Product
from .serializers import ProductSerializers
from rest_framework import generics


class ProductList(generics.ListCreateAPIView):
    serializer_class = ProductSerializers

    def get_queryset(self):
        queryset = Product.objects.all()

        return queryset

class ProductDetail(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = ProductSerializers
    queryset = Product.objects.all()

Serializers.py

from .models import Product, Category
from rest_framework import serializers


class CategorySerializers(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields="__all__"

class ProductSerializers(serializers.ModelSerializer):
    category_name = serializers.SerializerMethodField('get_category_name')
    
    def get_category_name(self, obj):
        if obj.category_id:
            return obj.category.name

    class Meta:
        model = Product
        fields = '__all__'

I am sending post request from react axios. axios.post(productListURL, data)

How do I send post request with category name:

name:"Coca Cola" ,
category:"Beverage"

Instead of

name: "Coca Cola",
category: 1

CodePudding user response:

Use this as the Product serializer

class ProductSerializers(serializers.ModelSerializer):
    category = serializers.SlugRelatedField(
        queryset=Category.objects.all(), slug_field="name"
    )
    class Meta:
        model = Product
        fields =['upc','name','description','category,'quantity','price']
  
  • Related