如果字符串字段不为空,如何连接表

时间:2018-12-05 01:34:06

标签: python django orm

我必须展示法律中的所有文章。除此之外,每篇文章都可以有描述。我必须显示所有文章和您的描述,但是当highlight description不为空时,我不知道如何添加描述和文章。

我的view

def details(request, pk):
 law = get_object_or_404(Law, pk=pk)    
 articles = Article.objects.filter(law=pk)
 articles = (
 Article
 .objects
 .filter(law=pk)
 .annotate(
     is_marked=Exists(
         Highlight
         .objects
         .filter(
             article_id=OuterRef('id'),
             user=request.user
         )
        )
     )
 )   
context = {
    'articles': articles,    
}
template_name = 'leis/details.html'
return render(request, template_name, context)

我的detail.html

<div class="article-post"> 
   {% for article in articles %}   
      {{article}}
   {% endfor %}
</div>

那是我的model

class Law(models.Model):
    name  = models.CharField('Name', max_length=100)
    description = models.TextField('Description', blank = True, null=True)

class Article(models.Model):
    article = models.TextField('Artigo/Inciso')
    number = models.IntegerField('Number', blank=True, null=True)
    law = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Law', related_name='articles')

该类随特定用户在特定法律中的特定文章中的描述一起保存:

class Highlight(models.Model):
    law = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Law', related_name='highlightArticles')
    article = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Article', related_name='highlightLaw')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='highlightUsers', related_name='highlightUsers')
    is_marked = models.BooleanField('Is it marked?', blank=True, default=False)
    description = models.TextField('Description', blank = True, null=True)

如何连接表格以显示所有文章以及特定用户对您的特定描述?

1 个答案:

答案 0 :(得分:0)

您可以尝试:

Article.objects.filter(law=pk, highlight__description__isnull=False).annotate(description=(F('highlight__description')))

它将返回所有highlight description不为null的Article,并且可以在您的视图中以{{article.description}}显示description