python - Add a boolean field if a row exists in another table? -


i have 2 tables called post , reply. users can create 1 response each post. models this:

class post(models.model):     name = models.charfield(max_length = 100)  class reply(models.model):     post = models.foreignkey(post, related_name = 'replies') 

now, have view returns posts, this:

class postlist(generics.listapiview):     permission_classes = (permissions.isauthenticated,)     queryset = post.objects.all()     serializer_class = postserializer 

and serializer posts:

class postserializer(serializers.modelserializer):     class meta:         fields = ('id', 'name') 

the results of view this:

[     {         "id": "1",         "name": "the first post"     },     {         "id": "2",         "name": "the second post"     } ] 

now, actual problem in question: i'd have boolean field in results that'd true if user has replied post, , false if hasn't. basically, result situation current user has replied first post not second post this:

[     {         "id": "1",         "name": "the first post",         "replied": "true"     },     {         "id": "2",         "name": "the second post",         "replied": "false"     } ] 

how achieve this? have hunch should implemented in serializer somehow, don't know how i'd that.

thanks in advance help!

piggybacking off of dydek's answer here.

you overwrite get_queryset in api view

class postlist(generics.listapiview):     ...     def get_queryset(self):         post.objects.all().extra(select={         'current_user_replies_count': 'select count(*) <reply table> where' +         'post_id=posts_post.id , owner_id = %s'                                   },select_params=(request.user.id,)) 

this add 'current_user_replies_count' property post objects in queryset.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -