I have a table with many records and am trying to create a complex query and hoping for some help here.
models.py
class Vote(models.Model):
is_annonymous = models.BooleanField(default=True)
开发者_如何学C vote = models.IntegerField()
created_by = models.ForeignKey(User, null=True, blank=True)
created_at = models.DateTimeField(null=True, blank=True)
ip_address = models.IPAddressField(null=True, blank=True)
#content type
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
query
all_votes = Vote.objects.filter(
~Q(created_by = None),
)
Am trying to return records from Vote where created_by is not null and created_by made his first vote. Meaning, I want to only return the Vote record if user made his first vote.
Am not sure how to do such a thing, usually, on SQL, I would have to do a sub query and count the user votes and if they are equal one then return the record.
Any idea how would I do that with django models?
You can do this grouping with a combination of the .values
and .aggregate
methods.
from django.db.models import Q, Min
votes = Vote.objects.filter(~Q(created_by=None).values('created_by').aggregate(min=Min('created_at'))
Once you have that, if you want to get the actual Vote
instances, you'll need to do another query and use the ids returned above.
For more information on this, check out the Django help section on aggregate and values.
try to left join Vote to itself on left_vote.created_by==right_vote.created_by and left_vote.id!=right_vote.id
and filter the records that have nulls on the right of the join.
精彩评论