Stupid.Fat.Cat
Stupid.Fat.Cat

Reputation: 11285

Get all rows where field matches another field in another table in django

Say that I have a table called watchlist, this contains a list of entities that I'm really concerned about:

class Watchlist(models.Model):
    entity = models.ForeignKey(Entity)
    objects = WatchlistManager()

    def __str__(self):
        return str(self.entity)

And say I have a list of alerts:

class DistinctAlert(models.Model):
    alert_type = models.ForeignKey(AlertType, db_index=True, on_delete=models.CASCADE)
    entities = models.ManyToManyField(to='Entity', db_index=True, through='EntityToAlertMap')
    has_unattended = models.BooleanField(default=True)
    latest_datetime = models.DateTimeField()

Disregarding what alert type is I'm trying to get all DistinctAlerts as long as the entity exists in the watchlist.

Something like this:

DistinctAlert.objects.filter(entities__in=Watchlist.objects.all()).all()

But of ocurse this doesn't work since they require entity objects instead of watchlist objects. What's the best approach for this? Should I do:

DistinctAlert.objects.filter(entities__in=[element.entity for element in self.all()]).all()

Not sure if iterating over every element and constructing the list outside is the right way to do it, or if it's possible to pass a queryset like so:

DistinctAlert.objects.filter(entities__in=Watchlist.objects.all()).all()

(the above example wouldn't work for me since they're watchlist objects and not entity objects)

Upvotes: 0

Views: 419

Answers (1)

knbk
knbk

Reputation: 53659

You can follow the backwards relation from Entity to Watchlist:

DistinctAlert.objects.filter(entities__watchlist__isnull=False)

Upvotes: 1

Related Questions