[Django]-How Do I Include ForeignKey in django-rest-framework POST

3👍

So I was able to answer this question by using some of Carter_Smith‘s advice – I am not 100% sure why this worked, but I added this create() method to my ArticleSerializer, and it worked:

def create(self, validated_data):
    # Override default `.create()` method in order to properly add `sport` and `category` into the model
    sport = validated_data.pop('sport_id')
    category = validated_data.pop('category_id')
    article = Article.objects.create(sport=sport, category=category, **validated_data)
    return article

My guess is that the PrimaryKeyRelatedField() tries to resolve sport_id and category_id as kwarg fields based on their name, when they should be just sport and category, and so overriding .create() allows you to fix that, while still allowing for a read_only field for sport and category. Hope this helps anyone else who has the same issue.

👤Hybrid

1👍

You need to override the serializer’s create method to accommodate your POST request. This probably isn’t what you’re looking for, but you haven’t included your sample request so we haven’t got much to go off of.

This would’ve been a comment had I been of high enough reputation.

Leave a comment