Django模型:一对多关系,跨越表 - 如何通过评论获取所有图书对象?

时间:2017-06-12 01:23:02

标签: python-2.7 django-models django-queryset one-to-many django-orm

我的问题:

我有一些django模型,它们设置了各种一对多的关系。我正在尝试检索所有有评论的书籍(我不想检索任何没有评论的书籍)。尽管我尝试做的事情看起来相对简单,但我在实现目标方面遇到了很大困难。我似乎无法正确理解如何跨表格,以及任何人可以提供的任何建议,以帮助我更好地了解如何获得所有所有 Book具有Review的对象存储

我的模特:

class User(models.Model):
    """Creates instances of a `User`."""

    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.CharField(max_length=50)
    password = models.CharField(max_length=22)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = UserManager() # Attaches custom `UserManager` methods to our `User.objects` object.

class Author(models.Model):
    """Creates instances of a `Author`."""

    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Book(models.Model):
    """Creates instances of a `Book`."""

    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE) # ties us into an author for the book. if author deleted, books delete too.
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


class Review(models.Model):
    """Creates instances of a `Review`."""

    description = models.CharField(max_length=500) 
    user = models.ForeignKey(User, on_delete=models.CASCADE) # ties to user, if user deleted, deletes all user reviews
    book = models.ForeignKey(Book, related_name="reviews") # book for review
    rating = models.IntegerField() # user rating between 1-5
    created_at = models.DateTimeField(auto_now_add=True) 
    updated_at = models.DateTimeField(auto_now=True) 
    objects = ReviewManager() # Attaches 'ReviewManager' to `Review.objects` methods.

我尝试过的事情:

我尝试过related_name="reviews"我的Review.book媒体资源,我尝试通过Book.objects.all().reviews_set.all()或类似的此类查询访问评论,使用{{1}我可能错过了某些事情/做错了。

期望的目标:

检索附有_set.all()的所有Book个对象(不检索没有评论的Review个对象。)

任何人都可以帮我指出正确的方向或告诉我我做错了什么吗?感谢您抽出时间阅读!

1 个答案:

答案 0 :(得分:0)

这是我收集所有至少有一篇评论的书籍的最佳解决方案。这似乎是在满足我的需求并回答了我原来的问题:

Book.objects.filter(review__gte=1).distinct()

这是说,从Book模型,获得评论gte(大于或等于)1的任何书籍 - 并确保它们是distinct(),即不重复。