简体   繁体   中英

Django Serializer Save models with foreign key relationships

I am trying to save a model object that has a foreign key referencing another table. Trying to write the serializer for the same, however can't wrap my head around how to do it and can't seem to find the right documentation either. 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 RMenuCategory model:

class RestaurantMenuSerializer(serializers.ModelSerializer):

    restaurant = serializers.PrimaryKeyRelatedField()

    class Meta:
        model = RMenuCategory
        fields = ('id', 'category_name', 'restaurant')

Making the api call with the json as:

{ "category_name" : "Italian", "restaurant_id" : 4}

This is not working when I try out the following in my view:

menu_cat = RestaurantMenuSerializer(data=data)
        if menu_cat.is_valid():
            category = menu_cat.save()
        else:
            exit()

更改restaurant_idrestaurant

{ "category_name" : "Italian", "restaurant" : 4}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM