python - django orm: retrieve object and check if it has a relation in one query -
i have application users can set post favorite. models defined this:
class userprofile(models.model): user = models.onetoonefield(user) favorites = models.manytomanyfield('post', through='favorite', related_name='favorited_by') class post(models.model): created_by = models.foreignkey(userprofile) body = models.textfield() class favorite(models.model): created_by = models.foreignkey(userprofile) post = models.foreignkey(post)
now i'm looking easy way query post , @ same time check if post favorited current user. i'm using following, far elegant, solution:
query = """ select p.id, p.body, p.created_by_id, f.created_by_id favorited main_post p left outer bring together main_favorite f on p.id = f.post_id , f.created_by_id = %s """; posts = post.objects.raw(query, [request.user.userprofile.id])
this results in column named 'favorited' either null value if post not favorited current user or id of current user if post favorited.
is there anyway done simpler , more elegant using django's orm?
django provides contenttypes framework might useful in case. , same work in more elegant way using generic foreign keys this.
**check examples @ https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/ similar you're trying accomplish
python sql django orm
No comments:
Post a Comment