Django Rest Framework - Get related model field in serializer


Answers

Django throws column cannot be null error when POSTing to REST Framework

Your serializer doesn't have an owner field and your view doesn't provide one. As it's non null in your model the DB will complain about this.

You should override the view's perform_update and add the owner as extra argument to the serializer

Question

I'm trying to return a HttpResponse from Django Rest Framework including data from 2 linked models. The models are:

class Wine(models.Model):

    color = models.CharField(max_length=100, blank=True)
    country = models.CharField(max_length=100, blank=True)
    region = models.CharField(max_length=100, blank=True)
    appellation = models.CharField(max_length=100, blank=True)

class Bottle(models.Model):

    wine = models.ForeignKey(Wine, null=False)
    user = models.ForeignKey(User, null=False, related_name='bottles')

I'd like to have a serializer for the Bottle model which includes information from the related Wine.

I tried:

class BottleSerializer(serializers.HyperlinkedModelSerializer):
    wine = serializers.RelatedField(source='wine')

    class Meta:
        model = Bottle
        fields = ('url', 'wine.color', 'wine.country', 'user', 'date_rated', 'rating', 'comment', 'get_more')

which doesn't work.

Any ideas how I could do that?

Thanks :)




I ran into a similar issue using Angular and Flask. This may because your CORS headers are not set correctly for your Django app which makes your Angular app not allowed to post to the backend. In Flask, I fixed it using this code:

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    return response

I'm not sure how to do this in Django, but this may be a great first stop for you since this is likely your issue.






Tags