views:

397

answers:

1

If I have

Model.objects.all()

I want to get only one object for any content_object=foo, object_id=N. How can I do that? Say I am ordering by -datetime. If I can get only one object in the queryset for any content_type=foo, object_id=N ... it should be the latest.. How to 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 take a queryset:

checkins = CheckIn.objects.filter(
        datetime__gte=datetime.datetime.now() -
        datetime.timedelta(hours=24),
)

this can give me all of the checkins within the last 24 hours but I only want 1 object PER content_type=foo and object_id=N.

+3  A: 

Do you want to find latest Model object after some filtering? What do you mean by object id ? Is it a foreign key? Or it is the Model id auto generated by django? I guess it is the later. In that case, you can use just id. This may help you (I am assuming that 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 apologize. Well, the question was not this clear at the beginning (and I am a newb). Here is a naive approach (I think you want distinct):

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
mshsayem
Add a check for length to this or it will blow up if it doesn't match any objects.
Anders Rune Jensen
nice, this could indeed be the best answer for now. If there is any more efficient way (not bringing everything in memory/python_objects) it would be better. But, way to come back with a solution, thanks.
skyl