Django Query - 如何使用基于根查询的值进行预取过滤器?
为了获得更好的性能,我使用预取选择来在一个查询中获取所有内容,如下所示:
profile = Profile.objects.only('id','series_following').prefetch_related(
Prefetch('books_reading', queryset=Book.objects.only('id').filter(
series_id=`series_following_id`), to_attr='books')).get(user=request.user_id)
我想让所有书籍都在使用 series_following 阅读,但我不知道如何将其放入过滤器。 这是我的模型:
class Profile(models.Model):
user = models.OneToOneField(User)
series_following = models.ForeignKey('Series')
books_reading = models.ManyToManyField('Book', related_name="readers_reading_book",
null=True, blank=True)
...
class Series(models.Model):
name = models.CharField()
...
class Book(models.Model):
name = models.CharField()
series = models.ForeignKey(Series)
...
For better performance, i use prefetch selected to get all in one single query like this:
profile = Profile.objects.only('id','series_following').prefetch_related(
Prefetch('books_reading', queryset=Book.objects.only('id').filter(
series_id=`series_following_id`), to_attr='books')).get(user=request.user_id)
I want to get all books are reading with series_following, but i dont know how to put it to filter.
Here are my models:
class Profile(models.Model):
user = models.OneToOneField(User)
series_following = models.ForeignKey('Series')
books_reading = models.ManyToManyField('Book', related_name="readers_reading_book",
null=True, blank=True)
...
class Series(models.Model):
name = models.CharField()
...
class Book(models.Model):
name = models.CharField()
series = models.ForeignKey(Series)
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定您的模型是否按照您预期的那样接线,但是像这样的怎么样?
这将为您提供与用户根据其个人资料关注的书籍具有相同系列的所有书籍。
Not sure your models are wired as you might expect them to be, but how about something like this?
That will get you all the books that a have the same series as the one a user is following based on their profile.
您可以通过以下方式获取
书籍
:You can obtain the
Book
s with: