Hi,
I’m new to Django and Danjo REST Framework and I’m trying to create a simple app that has two models related and a choice field.
So, I have this:
models.py
class Category(models.Model):
title = models.CharField(max_length=255, db_index=True)
class MenuItem(models.Model):
title = models.CharField(max_length=255, db_index=True)
price = models.DecimalField(max_digits=6, decimal_places=2, db_index=True)
category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1)
serializers.py
class CategorySerializer (serializers.ModelSerializer):
class Meta:
model = Category
fields = ['id','title']
class MenuItemSerializer(serializers.ModelSerializer):
category = CategorySerializer(read_only=True)
category_id = serializers.ChoiceField(write_only=True, choices=Category.objects.values_list('id','title'))
class Meta:
model = MenuItem
fields = ['id','title','price','category', 'category_id']
views.py
class CategoriesView(generics.ListCreateAPIView):
queryset = Category.objects.all()
serializer_class = CategorySerializer
class MenuItemView(generics.ListCreateAPIView):
queryset = MenuItem.objects.select_related('category').all()
serializer_class = MenuItemSerializer
def get(self, request):
items = MenuItem.objects.select_related('category').all()
serialized_item = MenuItemSerializer(items, many=True)
return Response(serialized_item.data, status.HTTP_200_OK)
class SingleMenuItem(generics.RetrieveUpdateDestroyAPIView):
queryset = MenuItem.objects.select_related('category').all()
serializer_class = MenuItemSerializer
def get(self, request, pk):
item = get_object_or_404(MenuItem, pk=pk)
serialized_item = MenuItemSerializer(item)
return Response(serialized_item.data, status.HTTP_200_OK)
urls.py
urlpatterns = [
path('menu-items', views.MenuItemView().as_view()),
path('menu-items/<int:pk>', views.SingleMenuItem().as_view()),
path('category', views.CategoriesView.as_view()),
]
This works fine, but when I try to access:
http://127.0.0.1:8000/api/menu-items/2
for example, and the category set to this item is 3, it shows the value of category 1 and not 3, and no mater what value I set, it always shows the first item of Category and not the one that actualy is on the dropdown.
I know that HTML has the “selected” option for the “select” form, but I’m really strugling in how to implement this in Django.