簡體   English   中英

Django:在另一個ManyToMany表中獲取具有相關行的objects.all()

[英]Django: get objects.all() with the related rows in another ManyToMany table

我有3種型號:

  • django普通用戶模型
  • 作者模型
  • UserAuthor模型,被視為前兩個模型之間的多對多關系,但具有其他字段(is_follow,review)

     class Author(models.Model): name = models.CharField(max_length=50) class UserAuthor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='userauthors') is_follow = models.BooleanField(default=0) review = models.TextField(max_length=500, blank=True, null=True) 

我的問題是關於如何使所有作者的每個作者內都有一個字段,以顯示經過身份驗證的用戶是否關注他。

我知道我可以使用related_name屬性,該屬性以某種方式返回按特定作者過濾的UserAuthor管理器,但如何獲取呢?

我的審判是:

class AuthorListView(ListView):
    model = Author

    def get_queryset(self):
        final_list = []
        authors_list = list(Author.objects.all())
        for author in authors_list:
            element = author.userauthors.filter(user=self.request.user)
            final_list.append(element)
        return final_list

我當然不喜歡這種解決方案,但是如何更好地做到這一點呢?

正如PeterDeGlopper在評論中指出的那樣,您可以使用注釋:

from django.db.models import Case, When, Value, BooleanField
followed_ids = UserAuthor.objects.\
    filter(user=self.request.user, is_follow=True).\
    values_list('author_id', flat=True)
final_list = Author.objects.annotate(followed=Case(
    When(id__in=followed_ids, then=Value(True)),
    default=Value(False),
    output_field=BooleanField()
))

現在,您可以訪問此查詢集的每個實例所followed的屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM