1

I have models:

class Reference(models.Model):
    name = models.CharField(max_length=50)

class Search(models.Model):
    reference = models.ForeignKey(Reference)
    update_time = models.DateTimeField(auto_now_add=True)

I have an instance of Reference and i need to get all last searches for the reference. Now i am doing it in this way:

record = Search.objects.filter(reference=reference)\
    .aggregate(max_date=Max('update_time'))
if record:
    update_time = record['max_date']
    searches = reference.search_set.filter(update_time=self.update_time)

It is not a big deal to use 2 queries except the one but what if i need to get last searches for each reference on a page? I would have got 2x(count of references) queries and it would not be good.

I was trying to use this solution https://stackoverflow.com/a/9838438/293962 but it didn't work with filter by reference

Community
  • 1
  • 1
kalombo
  • 861
  • 1
  • 9
  • 31

2 Answers2

0

You probably want to use the latest method. From the docs, "Returns the latest object in the table, by date, using the field_name provided as the date field."

https://docs.djangoproject.com/en/1.8/ref/models/querysets/#latest

so your query would be

Search.objects.filter(reference=reference).latest('update_time')
0

I implemented a snippet from someone in gist but I don't remember the user neither have the link. A bit of context:

I have a model named Medicion that contains the register of mensuration of a machine, machines are created in a model instance of Equipo, Medicion instances have besides of a Foreign key to Equipo, a foreign key to Odometro, this model serves as a kind of clock or metre, that's why when I want to retrieve data (measurements aka instances of Medicion model) for a certain machine, I need to indicate the clock as well, otherwise it would retrieve me a lot of messy and unreadable data.

Here is my implementation:

First I retrieve the last dates:

ult_fechas_reg = Medicion.objects.values('odometro').annotate(max_fecha=Max('fecha')).order_by()

Then I instance an Q object:

mega_statement = Q() # This works as 'AND' Sql Statement

Then looping in every date retrieved in the queryset(annotation) and establishing the Q statement:

for r in ult_fechas_reg:
        mega_statement |= (Q(odometro__exact=r['odometro']) & Q(fecha=r['max_fecha']))

Finally passed this mega statement to the queryset that pursues to retrieve the last record of a model filtered by two fields:

resultados = Medicion.objects.filter(mega_query).filter(
        equipo=equipo,
        odometro__in=lista_odometros).order_by('odometro', 'fecha') # lista_odometros is a python list containing pks of another model, don't worry about it.
Angie Alejo
  • 743
  • 9
  • 15