Boky
Boky

Reputation: 12064

Get results of the model only if child with Foreign key has records

I have two models as follows:

class Tutorial(models.Model):
    name = models.CharField(max_length=200, unique=True, blank=False, null=False)
    cover = models.ImageField(upload_to=tutorial_image_path)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_on = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=STATUS, default=1)

class Video(models.Model):
    name = models.CharField(max_length=200, unique=True, blank=False, null=False)
    tutorial = models.ForeignKey(Tutorial, on_delete=models.DO_NOTHING, blank=False, null=False)
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, blank=False, null=False)
    iframe = models.CharField(max_length=500, blank=False, null=False)
    description = models.TextField(blank=True, null=True)
    created_on = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=STATUS, default=1)

class Meta:
    ordering = ['-created_on']

def __str__(self):
    return self.name

I want to get all Tutorials where there is at least one video in Video model

Something as follows:

results = Tutorial.objects.filter(id__in=Video.objects.filter....)

Any idea how to do that?

Upvotes: 0

Views: 30

Answers (1)

Higor Rossato
Higor Rossato

Reputation: 2046

You can make use of isnull

results = Tutorial.objects.filter(video__isnull=False).distinct()

Maybe (because I didn't test this) you could also do:

results = Tutorial.objects.select_related("video").filter(video__isnull=False).distinct()

Upvotes: 1

Related Questions