Home > Blockchain >  Filter foreign key in DetailView Django
Filter foreign key in DetailView Django

Time:03-20

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

CodePudding user response:

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
  • Related