André Fratelli
André Fratelli

Reputation: 6068

make query return related query

I have this model which tells me which users liked which images:

class Image:
    url = ....
    likes = models.ManyToManyField(get_user_model())

This way users can like any number of images and multiple users can like the same image.

Now I want to return sets of images to the client but indicating which of them the currently logged user liked. So instead of having a list of Images (which would only indicate the URL) I want a list of objects with a URL and a boolean field, indicating if a specific user liked the respective image.

Upvotes: 1

Views: 51

Answers (1)

A Sz
A Sz

Reputation: 1094

Are you looking for something like

list = [ (img, bool(img.likes.filter(uid=CURRENT_UID))   for   img   in   Image.objects.all() ]

Your milage might vary: if you want to restrict the set of images, use a different filter instead of Image.objects.all(). Your user property might be called differently than uid, etc.

Or, alternatively if you are on 1.4 or higher, you can use the prefetch_related option on the QuerySet, see the Django documentation on it here.

Upvotes: 1

Related Questions