Search code examples
pythondjangodjango-modelsdjango-rest-frameworkcoursera-api

Django->IntegrityError when Creating a record with a foreign key assign to it model


So I am Following a course of Django API and at last of my project is to create API for a Little Lemon restaurant.I have downloaded the Same Project Source code and now implementing it on my side.Currently i am stuck on a issue for 2 days now i have tried chatgpt, stack-overflow but there are no concrete solution.so the problem is i can't insert a menu-item in the DB. Beacuse it is thorwing an error of

IntegrityError at /api/menu-items NOT NULL constraint failed: LittleLemonAPI_menuitem.category_id

**This error occurs when i try to insert a menu-item using the Insomia. But if i create the same item using the Super User it is created.

This is my View.**

class MenuItemListView(generics.ListCreateAPIView):
    queryset = MenuItem.objects.all()

    serializer_class = MenuItemSerializer

    def get_permissions(self):
        permission_classes = [IsAuthenticated]
        if self.request.method != 'GET':
            permission_classes = [IsAuthenticated, IsManager | IsAd

This is my Model:

class MenuItem(models.Model):
    title = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    featured = models.BooleanField(db_index=True)
    category = models.ForeignKey(Category, on_delete=models.PROTECT)

    class Meta:
        unique_together = [['title', 'category']]
        
    def __str__(self):
        return self.title

This is my Serializer

class MenuItemSerializer(serializers.ModelSerializer):
    def validate_category(self, value):
        try:
            Category.objects.get(pk=value)
            return value
        except Category.DoesNotExist:
            raise serializers.ValidationError('Invalid category ID.')

    class Meta:
        model = MenuItem
        fields = ['id', 'title', 'price', 'featured', 'category']
        depth = 1

This is my Json Request:

{
    "title": "Spring Rolls",
    "price": "5.99",
    "featured": true,
    "category": 1
}

NOTE: I have created the Category using the API but when i ty to create menu-item it is giving me this error. beacuse of foregin key constraint.

I have Tired Deleting the Migration and flushing the data and restarted the process but i got the same result.
I have also tried chatgpt but it gave me no concrete solution.

when i try to create menu-item using the superuser it is create.
but when i try to create the menu-item using API it gives me

IntegrityError at /api/menu-items NOT NULL constraint failed: LittleLemonAPI_menuitem.category_id

Solution

  • class MenuItemSerializer(serializers.ModelSerializer):
    category = serializers.SlugRelatedField(slug_field='id', queryset=Category.objects.all())
    
    class Meta:
        model = MenuItem
        fields = ['id', 'title', 'price', 'featured', 'category']
        depth = 1
    

    i just got the answer from the ChatGPT you will have to modify the serializers to handle the category id.

    The SlugRelatedField is a field that represents the target of the relationship using a "slug" attribute. In this context, "slug" can be any field on the related model that uniquely identifies instances of the related mode This specifies which field on the related model (Category) should be used as the "slug" for representation. Here, it's using the id field of the Category model. This means that when you serialize a MenuItem instance, the category field will be represented by the id of the related Category instance.