sofx
sofx

Reputation: 171

how to exclude equal column in django model?

I have a model with 2 foreign filed point to the same model:

class Student(models.Model):
    old_school = model.ForeignField(school)
    new_school = model.ForeignField(school)

I want to find student who's old_school != new_school. I tried these:

Student.objects.all().exlude(old_school = new_school)
Student.objects.all().exlude(self.old_school = self.new_school)

but none of them work. It seems model manager can not refer to new_school. Is there any method to do such query? Or I have to manually check not equal in python code:

if student.old_school != student.new_school:
   s_list.append(student)

Upvotes: 1

Views: 765

Answers (2)

Zach
Zach

Reputation: 151

This can also be accomplished without the Q object if you want to import one less thing.

from django.db.models import F

Student.objects.exclude(old_school=F('new_school'))

In my testing it generated the same MySQL on the backend.

Upvotes: 1

alecxe
alecxe

Reputation: 473873

You can achieve this by using Q and F:

Student.objects.filter(~Q(old_school=F('new_school')))

Q helps to build not equal condition, while F helps to reference another model field.

Upvotes: 3

Related Questions