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