如何在Django中创建同一类别的帖子列表

时间:2019-04-13 13:18:38

标签: django django-views

我尝试在帖子详细信息中创建同一类别的帖子列表。类似于相关帖子。

我尝试这样做:

观看次数:

subject = get_object_or_404(Subject, slug=slug)
subject_board_ids = subject.board.values_list('id', flat=True)
related_subjects = Subject.objects.filter(board__in=subject_board_ids).exclude(id=subject.id)

型号:

class Subject(models.Model):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    slug = AutoSlugField(populate_from='title', unique=True)
    body = HTMLField(blank=True, verbose_name='Treść')
    image = models.ImageField(upload_to='subject', null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name='subjects', verbose_name='Kategoria')
    votes = GenericRelation(LikeDislike, related_query_name='subjectsvotes')
    featured = models.BooleanField(default=False)

实际结果是错误:“ Board”对象没有属性“ values_list”。

我尝试创建最多6条相关帖子。

1 个答案:

答案 0 :(得分:3)

您当然会出错,因为您的主题链接是使用FK进行的。然后,表达式 subject.board 给了您“ Board”对象而不是“ Board” Queryset。要获取相关主题,请使用:

subject = get_object_or_404(Subject, slug=slug)
related_subjects = Subject.objects.filter(board=subject.board).exclude(id=subject.id)