Peter Greene
Peter Greene

Reputation: 11

filter objects which are not members of other objects

I tried to get an answer to this previously with no luck.

I have a model that looks like (simplified):

class Answer(models.model):
    previous = models.ForeignKey('self')
    id = IntegerField()

How can I define a filter to find Answer objects which are not the previous Answer for any other Answer object.

For example:

I have a set of answers [A1, A2, A3, A4] with:

A1.previous = A2
A2.previous = A4
A3.previous = A1
A4.previous = A1

I want to find A3 since this is the only one in the set which does not have X.previous = A3 where X is in the set

Upvotes: 1

Views: 45

Answers (1)

professorDante
professorDante

Reputation: 2405

Something like this might work:

Answer.objects.exclude(previous__in=Answer.objects.all().values_list('previous', flat=True))

Nesting the QS might be very expensive though, see here.

Upvotes: 1

Related Questions