Django Serializer Save Models with Foreign Key Relations

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)
    # And so on

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()
+4
source share
1 answer

Change restaurant_idto restaurant:

{ "category_name" : "Italian", "restaurant" : 4}
+3
source

Source: https://habr.com/ru/post/1598946/


All Articles