简体   繁体   中英

Django filter exclude foreign key

I'm creating a news website which has two models:

  1. News
  2. BestNews.

BestNews has a foreign key of News .

News stands for all the news and BestNews is stands for the recommended news.

Now I have rendered News list and Best News list in index.html.But some news in these two parts are duplicated.

I hope news that in Best News list, will not appear in News list, and once I have removed the news from the Best News in admin, the news which has been removed from best news will appear News list.

Here is my News model:

class News(models.Model):
    title = models.CharField(max_length=100, verbose_name='标题') 
    content = UEditorField(verbose_name="内容", width=600, height=300, imagePath="news/ueditor/", filePath="news/ueditor/", default='')

    class Meta:
        verbose_name = "新闻"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

Here is my Best News model:

class Best(models.Model):
    select_news = models.ForeignKey(News, on_delete=models.CASCADE, related_name='select_news',verbose_name='要闻')  
    SELECT_REASON = (
        ('左一', '左一'),
        ('左二', '左二'),
    )
    select_reason = models.CharField(choices=SELECT_REASON, max_length=50, null=False)  

    class Meta:
        verbose_name = "精选"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.select_reason + '-' + self.select_news.title

Here is my News list view:I get News list and Best News list in one view.

class NewsView(View):

    def get(self, request):
        all_news = News.objects.all().order_by('-pk')
        bestnews1 = Best.objects.filter(select_reason="左一")[0].select_news
        bestnews2 = Best.objects.filter(select_reason="左二")[0].select_news
      
        return render(request, 'index.html', {
            'all_news': news,
             'bestnews1':bestnews1,
             'bestnews2':bestnews1,
        })
all_news = News.objects.all().order_by('-pk')

to

all_news = News.objects.filter(select_news__isnull=True).order_by('-pk')

free advice:

change

bestnews1 = Best.objects.filter(select_reason="左一")[0].select_news

to

bestnews1 = Best.objects.filter(select_reason="左一").first()
bestnews1_new = None if bestnew1 is None else bestnews1.select_news
return render(request, 'index.html', {
            'all_news': news,
             'bestnews1_new':bestnews1_new,
             'bestnews2_new':bestnews2_new,
        })

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