I am trying to save a model object that has a foreign key referencing another table. Trying to write a serializer for the same thing, however, can’t wrap my head around how to do this, and it seems it cannot find the correct documentation. My model objects:
class Restaurant(models.Model):
name = models.CharField(null=False, max_length=255)
min_order = models.CharField(null=False, max_length=255)
class RMenuCategory(models.Model):
category_name = models.CharField(null=False, max_length=255)
restaurant = models.ForeignKey('Restaurant')
My serializer class for model RMenuCategory:
class RestaurantMenuSerializer(serializers.ModelSerializer):
restaurant = serializers.PrimaryKeyRelatedField()
class Meta:
model = RMenuCategory
fields = ('id', 'category_name', 'restaurant')
Making an api call using json as:
{ "category_name" : "Italian", "restaurant_id" : 4}
This does not work when I try to do the following:
menu_cat = RestaurantMenuSerializer(data=data)
if menu_cat.is_valid():
category = menu_cat.save()
else:
exit()
source
share