在Django的基于新闻Feed的数据模型中查询关注者 [英] Querying for followers in news-feed-based data model in Django

查看:122
本文介绍了在Django的基于新闻Feed的数据模型中查询关注者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中有以下(简化的)模型,它与Pinterest数据模型非常相似:

  class UserProfile 
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)

类项目(models.Model):
collections = models.ManyToManyField(Collection,blank = True,null = True)

我有一个用户模型,用户与用户映射1-1的UserProfile模型,具有所有者和关注者的集合模型以及可以作为多个集合的一部分的项目。我正在努力确定如何在Django中执行以下查询:



获取给定用户的所有关注者。追随者的定义是遵循至少一个由该特定用户拥有的集合的定义。



获取用户遵循的所有集合的所有不同项目。 p>

我不知道我是否可以在单个查询中执行这些操作,或者我必须在几个查询中分解它?什么是最好的方法,有什么折衷?



感谢任何帮助。

解决方案

第一个将是这样的我想:

  User.objects.filter(collection_owner__owner = '用户')

后者应该是这样的:

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

然而,您应该知道,这些类型的查询不会缩放到大量的数据。这样做需要相当多的黑客...


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

这篇关于在Django的基于新闻Feed的数据模型中查询关注者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆