Home > Blockchain >  DRF nested serialization without raw sql query
DRF nested serialization without raw sql query

Time:10-29

I've stuck with this problem for few days now. Tried different approaches but without success. I have two classes - Poll and PollAnswer. Here they are:

class Poll(Model):
    title = CharField(max_length=256)
class PollAnswer(Model):
    user_id = CharField(max_length=10)
    poll = ForeignKey(Poll, on_delete=CASCADE)
    text = CharField(max_length=256)

what is the right way to get list of polls which have answers with used_id equal to the certain string with nested list of that user's answers? like this:

{
    'poll_id': 1,
    'answers' : {
        'user1_answer1: 'answer_text1',
        'user1_answer2: 'answer_text2',
        'user1_answer3: 'answer_text3',    
    },
}

and if it's the simple question i probably need some good guides on django orm.

the first thing i tried was to make serializer's method (inherited from drf's ModelSerializer) but got an error that this class can't have such method. after that i tried to use serializer's field with ForeignKey but got polls nested in answers instead. right now i believe i can make Polls.objects.raw('some_sql_query') but that's probably not the best way.

CodePudding user response:

Your problem is described in documentation (also best practise). You can use nested serializer:

https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers

otherwise if u want to keep nested answers as you described: i would use serializer method field

https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

then do a little loop over your answers ... and return whatever format you want to.

CodePudding user response:

You need to take a look at this section if you really really need to do it this way, basically you need to use F expressions to get your desired output format, however I would strongly recommend you use a serializer for this, link

  • Related