代码之家  ›  专栏  ›  技术社区  ›  woe-dev.

django按作者查询的文章集用户正在跟踪

  •  0
  • woe-dev.  · 技术社区  · 7 年前

    我有两个模型

    class Account(AbstractBaseUser, PermissionsMixin):
        followers = models.ManyToManyField(
            'Account', related_name='followers',
            blank=True,
        )
        following = models.ManyToManyField(
            'Account', related_name='following',
            blank=True,
        )
    

    class Article(models.Model):
        author = models.ForeignKey(
            settings.AUTH_USER_MODEL,
            null=True,
            blank=True,
        )
    

    我正在编写一个应用程序,其中用户相互订阅并创建文章。

    我怎样才能提出一个要求,从那些我订阅的人那里接收所有的文章? 我想做点什么: (伪代码)

    user = self.get_object()
    articles = Article.objects.filter(author=user.followers.all())
    

    但我知道这是不对的

    3 回复  |  直到 7 年前
        1
  •  3
  •   neverwalkaloner    7 年前

    您可以先获取以下列表,然后使用 __in :

    user = self.get_object()
    following = user.following.values_list('id', flat=True)
    articles = Article.objects.filter(author_id__in=following)
    
        2
  •  3
  •   Alasdair    7 年前

    你不需要两个多对多的字段。

    例如,可以删除 followers 多对多字段,然后通过使用 following 场。

    class Account(AbstractBaseUser, PermissionsMixin):
        following = models.ManyToManyField(
            'Account', 
            related_name='followers',
            blank=True,
        )
    

    然后,可以使用双下划线表示法对多对多字段进行筛选:

    articles = Article.objects.filter(author__followers=user)
    
        3
  •  0
  •   user63053    7 年前

    您可能希望将追随者和跟踪字段分为两个类。 (伪代码)

    class Following():
        author_id = models.foreignkey('Author')
        following_authors = models.integerfield('Following_Authors')
    

    循环到您要跟踪的所有作者,并附加到列表中。当然,您的文章应该有一个已发布文章的文章字段。

    AuthorOfArticle = Author.objects.get(author='author to get all following')
    
    FollowingAuthorsObj = Following.objects.filter(author=AuthorOfArticle.author) #get all the authors you are following.
    
    ArticlesOfAuthor=[] #create a list variable
    for authors in FollowingAuthorsObj: #loop through all you are following
        ArticlesOfAuthor.append(Article.objects.filter(author=authors[0].author)) 
    #save it to a list of all articles.
    

    希望这有帮助。