Django:基于相关字段的不同查询集
在我的 Django 应用程序中,我允许用户按类别创建电影集合。这用 3 个模型来表示:Movie、Collection 和 Addition(Addition 模型存储电影、Collection 和用户实例)。所有三个模型的简化版本如下。
class Movie(models.Model):
name = models.CharField(max_length=64)
class Collection(models.Model):
name = models.CharField(max_length=64)
user = models.ForeignKey(User)
class Addition(models.Model):
user = models.ForeignKey(User)
movie = models.ForeignKey(Movie)
collection = models.ForeignKey(Collection)
例如,用户可以创建一个名为“80 年代电影”的集合,并将电影“印第安纳琼斯”添加到他们的集合中。
我的问题是:如何根据一组查询过滤器显示不同的电影列表?现在,我收到了一堆已添加到多个收藏中的电影的副本。我通常会使用 unique() 来获取不同的对象,但在这种情况下,我需要不同的电影而不是不同的添加内容,但我需要查询添加模型,因为我希望允许用户查看其朋友添加的电影。
我是否以最佳方式设置模型?任何建议/帮助将不胜感激。
谢谢!
In my Django app I allow users to create collections of movies by category. This is represented using 3 models, Movie, Collection, and Addition (the Addition model stores movie, collection, and user instances). Simplified versions of all three models are below.
class Movie(models.Model):
name = models.CharField(max_length=64)
class Collection(models.Model):
name = models.CharField(max_length=64)
user = models.ForeignKey(User)
class Addition(models.Model):
user = models.ForeignKey(User)
movie = models.ForeignKey(Movie)
collection = models.ForeignKey(Collection)
So for example a user could create a collection called "80's movies", and add the movie "Indiana Jones" to their collection.
My question is: how do I display a distinct list of movies based on a set of query filters? Right now I am getting a bunch of duplicates for those movies that have been added to more than one collection. I would normally use distinct() to get distinct objects, but in this case I need distinct movies rather than distinct additions, but I need to query the Addition model because I want to allow the user to view movies added by their friends.
Am I setting up my models in an optimal way? Any advice/help would be much appreciated.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一的。我认为您在这里不需要
Addition
模型。您尝试创建多对多关系,但有记录 这样做的方法:第二。文档说:“引用“反向”关系,只需使用模型的小写名称即可”。
所以答案是(对于上面的设置):
First. I don't think you need
Addition
model here. You try to create many-to-many relation, but there's documented way of doing this:Second. The documentation says: "To refer to a "reverse" relationship, just use the lowercase name of the model".
So the answer is (for the setup above):