简体   繁体   中英

Filter foreign key in DetailView Django

I ran into a problem with the queryset query, I need to display certain tags for each article that are related to this article. Each article has tags associated with the article id.

model.py

class NewsDB(models.Model):
    title = models.CharField('Название',max_length=300)
    text = models.TextField('Текст статьи')
    img = models.ImageField('Фото',upload_to='News',null='Без фото')
    avtor = models.ForeignKey('Journalist', on_delete=models.PROTECT)
    date = models.DateField()
    def __str__(self):
        return self.title
    class Meta:
        verbose_name = 'News'
        verbose_name_plural = 'News DataBase'

class Hashtags(models.Model):
    News=models.ForeignKey('NewsDB',on_delete=models.PROTECT)
    Hashtag=models.CharField('Хештег',max_length=150,null='Без темы')
    def __str__(self):
        return self.Hashtag

view.py

class Show_post(DetailView):
    model = NewsDB
    template_name = 'navigation/post.html'
    context_object_name = 'newsDB'
    def get_context_data(self,**kwargs):
        hashtags = super(Show_post,self).get_context_data(**kwargs)
        hashtags['hashtags_list'] = Hashtags.objects.filter(News=self.pk)
        return hashtags

you need to specify the kwargs

class Show_post(DetailView):
    model = NewsDB
    template_name = 'navigation/post.html'
    context_object_name = 'newsDB'
    def get_context_data(self,**kwargs):
        hashtags = super(Show_post,self).get_context_data(**kwargs)
        # the problem is in this line
        hashtags['hashtags_list'] = Hashtags.objects.filter(News=self.kwargs['pk'])
        return hashtags

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM