Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add a condition of comparing two fields of the model itself in Django model query

As mentioned by the title, in Django:

Say I have a model name QuestionRecord, with two fields: full_score and actual_score. I want to realize the SQL:

select * from QuestionRecord as QR where QR.full_score!=QR.actual_score.

Maybe using raw sql is OK, but I want to implement it like this:

class QuestionRecord_QuerySet(models.query.QuerySet):
    def incorrect(self):# Find out those whose full_score and actual_score are not equal
        return self.filter(...) # **What should I write here??**

class QuestionRecord_Manager(models.Manager):
    def get_query_set(self):
        return QuestionRecord_QuerySet(self.model)

class QuestionRecord(models.Model):
    objects = QuestionRecord_Manager()

Is there any way to do it?

like image 689
firstprayer Avatar asked Jun 11 '13 09:06

firstprayer


People also ask

How do you make two fields unique in Django?

Using the constraints features UniqueConstraint is preferred over unique_together. From the Django documentation for unique_together : Use UniqueConstraint with the constraints option instead. UniqueConstraint provides more functionality than unique_together.

Does Django ORM support subquery?

Django allows using SQL subqueries.

What is Select_related in Django?

Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects. The select_related method is for ForeignKey and OneToOne fields.


1 Answers

Sure, that's what the "F" object is for!

from django.db.models import F

# snip

    return self.exclude(full_score = F('actual_score'))

Use QuerySet.exclude here, as you want to not get the results that match.

If you really want to use QuerySet.filter, you can use a negated "Q" object: self.filter(~Q(full_score = F('actual_score'))).

like image 67
Thomas Orozco Avatar answered Oct 26 '22 22:10

Thomas Orozco