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?
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.
Django allows using SQL subqueries.
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.
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')))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With