2

Following are my files. It is simply adding products based on subcategories and categories. Everything is working fine but the data is not being saved in the database. I am not sure where I am going wrong.

models.py

from django.db import models

class Category(models.Model):
    category = models.CharField(max_length=200)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='children')

    class Meta:
        unique_together = ('parent' , 'category')

    def __str__(self):
        return self.category

class SubCategory(models.Model):
    subcategory = models.CharField(max_length=200)
    category = models.ForeignKey('Category', null=True, blank=True)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='subchilren')

    class Meta:
        unique_together = ('parent' , 'subcategory')

    def __str__(self):
        return self.subcategory

class Product(models.Model):
    name = models.CharField(max_length=200)
    category = models.ForeignKey('Category', null=True, blank=True)
    subcategory = models.ForeignKey('SubCategory', null=True, blank=True)

    def __str__(self):
        return self.name

views.py

class AddProducts(APIView):
    serializer_class = AddProductsSerializer
    def post(self, request, format=None):
        data = request.data
        serializer = AddProductsSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            return Response(new_data)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

serializers.py

class AddProductsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('id', 'name', 'category', 'subcategory')

        def create(self, validated_data):
            return Product.objects.create(**validated_data)

        def update(self, instance, validated_data):
            instance.name =  validated_data.get('name', instance.name)
            instance.category = validated_data.get('category', instance.category)
            instance.subcategory = validated_data.get('subcategory', instance.subcategory)
            instance.save()
            return instance
Yathartha Joshi
  • 716
  • 1
  • 14
  • 29
  • if you open up the django shell, are you able to create a `Product` model via `p = Product.objects.create(name = 'some_name' ... )` and see it in the database? – Jason Oct 31 '17 at 20:27
  • No. I tried `f = Product.objects.create(name='Shorts',category='Clothings',subcategor ...: y='Female')`, but it gave `ValueError: Cannot assign "'Clothings'": "Product.category" must be a "Category" instance.` I guess this is because field category is a foreign key, but I don't know how to do that for foreign key. – Yathartha Joshi Oct 31 '17 at 20:34
  • 1
    yes, because you have ForeignKey as the field type for those fields. You need to get an instance of those models and use in the create call. Check out https://stackoverflow.com/questions/30017334/django-foreign-key-must-be-an-instance – Jason Oct 31 '17 at 20:35
  • And how can I do that? – Yathartha Joshi Oct 31 '17 at 20:36
  • Something like: `cat = Category.objects.first(); sub_cat = SubCategory.obects.first(); p = Product.objects.create(name='Shorts', category=cat, subcategory=sub_cat)` – ettanany Oct 31 '17 at 21:02

1 Answers1

2
    if serializer.is_valid(raise_exception=True):
        serializer.save()
        new_data = serializer.data
        return Response(new_data)

add serializer.save() will call serializer create method when serializer has no instance.

Ykh
  • 7,567
  • 1
  • 22
  • 31
  • It worked! but I didn't understand why this happened. Before I used `instance.save()`, why was it not saved then, and what difference `serializer.save()` created? – Yathartha Joshi Nov 01 '17 at 04:12
  • 1
    `serializer.save()` will call `create` method in your `AddProductsSerializer` – Ykh Nov 01 '17 at 05:06