Querying for followers in news-feed-based data mod

2019-09-02 16:28发布

问题:

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