Django select distinct只有具有指定外键id的相关对象

时间:2016-07-20 07:07:22

标签: django django-queryset

我需要列出具有指定类别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')

1 个答案:

答案 0 :(得分:1)

试试这个

models.Fedsubj.objects.filter(articles__isnull=False, articles__id_section=some_sectionart_instance).distinct()