Django过滤器排除外键 [英] Django filter exclude foreign key

查看:166
本文介绍了Django过滤器排除外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个具有两个模型的新闻网站:

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


  1. News

  2. BestNews。

BestNews 的外键为 News

News

现在,我已经在index.html中呈现了新闻列表和最佳新闻列表。但是这两部分中的一些新闻是重复的。

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.

这是我的新闻模型:

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')

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






免费建议:


free advice:

更改

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

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,
        })

这篇关于Django过滤器排除外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆