Django select distinct 只有具有指定外键 id 的相关对象
Django select distinct only has related objects with specified foreign key id
我需要列出具有指定类别 ID 的相关对象的区域。
我写的查询对所有类别都是这样:
models.Fedsubj.objects.filter(articles__isnull=False).distinct()
但是如何指定类别 (id_section
)?
型号
class Fedsubj(models.Model):
id = models.AutoField(primary_key=True)
fesname = models.CharField(max_length=255)
fessort = models.IntegerField()
fescont = models.TextField()
class SectionArt(MPTTModel):
id_section = models.AutoField(primary_key=True)
title_sec = models.CharField(max_length=250)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
class Articles(models.Model):
id_art = models.AutoField(primary_key=True)
title_art = models.CharField(max_length=250)
id_section = TreeForeignKey(SectionArt, db_column='id_section')
fesid = models.ForeignKey(Fedsubj, db_column='fesid')
试试这个
models.Fedsubj.objects.filter(articles__isnull=False, articles__id_section=some_sectionart_instance).distinct()
我需要列出具有指定类别 ID 的相关对象的区域。
我写的查询对所有类别都是这样:
models.Fedsubj.objects.filter(articles__isnull=False).distinct()
但是如何指定类别 (id_section
)?
型号
class Fedsubj(models.Model):
id = models.AutoField(primary_key=True)
fesname = models.CharField(max_length=255)
fessort = models.IntegerField()
fescont = models.TextField()
class SectionArt(MPTTModel):
id_section = models.AutoField(primary_key=True)
title_sec = models.CharField(max_length=250)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
class Articles(models.Model):
id_art = models.AutoField(primary_key=True)
title_art = models.CharField(max_length=250)
id_section = TreeForeignKey(SectionArt, db_column='id_section')
fesid = models.ForeignKey(Fedsubj, db_column='fesid')
试试这个
models.Fedsubj.objects.filter(articles__isnull=False, articles__id_section=some_sectionart_instance).distinct()