Django - How to get only 2 objects for combining fields with a queryset
If I have
Model.objects.all()
I only want to get one object for any content_object = foo, object_id = N. How can I do this? Let's say I order this time. If I can only get one object in the queryset for any content_type = foo, object_id = N ... it should be the last one. How do I specify that I only want 1 object for any combination of content_object and object_id?
class CheckIn(models.Model):
...
owner = models.ForeignKey('auth.User')
datetime = models.DateTimeField(editable=False, auto_now=True)
...
# This is the object that should be geocoded, hopefully
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
class Meta:
ordering=( '-datetime', )
Then, to execute a set of queries:
checkins = CheckIn.objects.filter( datetime__gte=datetime.datetime.now() - datetime.timedelta(hours=24), )
this might give me all the checks for the last 24 hours, but I only want 1 PER object content_type = foo and object_id = N.
source to share
Do you want to find the last model object after some filtering? What do you mean by object identifier? Is this a foreign key? Or is it a django generated model id? Probably later. In this case, you can only use id. This might help you (I assume you have at least these fields in your model: content_object, DateField):
Model.objects.filter(content_object=foo,id=N).order_by(dateField)[0]
EDIT:
I'm sorry. Well, the question wasn't clear at first (and I'm a beginner). Here's a naive approach (I think you want to differentiate):
d={}
[d.setdefault(str(a.content_type)+str(a.object_id),a) for a in checkins ]
d.values() # this gives your desired list of distinct objects
source to share