Reputation: 171
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
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