简体   繁体   中英

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

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM