Querying for followers in news-feed-based data model in Django

白昼怎懂夜的黑 提交于 2019-12-13 21:21:30

问题


I have this following (simplified) model in Django which is very similar to the Pinterest data model:

class UserProfile(models.Model):
    user = models.OneToOneField(User)

class Collection(models.Model):
    owner = models.ForeignKey(User,related_name='collection_owner')
    followers = models.ManyToManyField(User, related_name='collection_followers', null=True, blank=True, default = None)

class Item(models.Model):
    collections = models.ManyToManyField(Collection,blank=True,null=True)

I have a User model, a UserProfile model that maps 1-1 with a user, a Collection model which has an owner and followers and items that can be part of multiple collections. I'm struggling with determining how to execute the following queries in Django:

Get all the followers of a given user. The definition of a follower is one that follows at least one collection that is owned by that particular user.

Get all the distinct items of the collection a user follows.

I'm not sure if I can do these in a single query or do I have to break it up in several queries? What would be the best approach and are there any trade offs?

Thanks for any help.


回答1:


The first would be something like this I think:

User.objects.filter(collection_owner__owner='the user')

The latter should be something like this:

Item.objects.filter(collections__followers='the user').distinct()

You should be aware however that these type of queries do not scale to large amounts of data. Doing that will require quite a bit of hacking...



来源:https://stackoverflow.com/questions/19128171/querying-for-followers-in-news-feed-based-data-model-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!