3

I have two simple models: User (standard Django User) AND class Post (models.Model):

class Post (models.Model):
   name = models.CharField(max_length=100)
   user = models.ForeignKey(User, on_delete=models.CASCADE)
   def __str__(self):
    return self.name

My front end (SPA) sends a request to get all posts, so my Django API would go and fetch Post.objects.all(). However I would like to also pull in the User.username into the response. My understanding is that I can do this by running:

posts=Post.objects.select_related('user').all()

When I run posts.query from the resulting SQL query I can see that the User fields are being pulled in, however I can't seem to be able to see them when I try to serialize this data. Am I missing something very basic here? What is the way to serialize the related data together with the parent data and send it out with the DRF Response? I have tried approach described in this article, but the serializer built with this approach does not seem to return related data for me: http://ses4j.github.io/2015/11/23/optimizing-slow-django-rest-framework-performance/

user3357094
  • 259
  • 2
  • 7

1 Answers1

4
PostSerializer():
    user = UserSerializer()
    class Meta:
        model = Post
        fields = ('name', 'user')
Spatz
  • 18,640
  • 7
  • 62
  • 66
Roman Nozhenko
  • 698
  • 8
  • 21