Django query to select a parent with non-zero children

I have a model with a foreign key for myself as follows:

class Concept(models.Model):
    name = models.CharField(max_length=200)
    category = models.ForeignKey('self')

But I can’t understand how I can choose all the concepts that have non-zero meanings for children. Is this possible using the django QuerySet APIs or should I write my own SQL?

+3
source share
3 answers

If I understand correctly, everyone Conceptcan have the other Conceptas a parent, and it is set in the field category.
In other words, a Conceptwith at least one child will be referenced at least once in the field category.

, Django - ; , , SELECT * FROM CONCEPTS WHERE CONCEPTS.ID IN (SELECT CATEGORY FROM CONCEPTS); - , Django:

Concept.objects.filter(pk__in=Concept.objects.all().values('category'))

, , Django, ; :

Concept.objects.filter(id__in=list(Concept.objects.all().values('category')))

, - , Oracle 1000 .

+3

- :

concepts = Concept.objects.exclude(category=None)
+2

, , category. ( null=True ), :

Concept.objects.filter(category__isnull=False)
+2

Source: https://habr.com/ru/post/1740790/


All Articles