Oleg
Oleg

Reputation: 847

Get value from model

I have 2 issues.

First, I have the model with field obj_id, text, creation_date.

In table it looks like:

obj_id text creation_date

1      '1'  01.01.2016
1      '2'  01.02.2016
2      '3'  01.03.2016
2      '4'  01.04.2016

I need return list of 'obj_id' with MAX 'creation_date'.

After that I need execute SQL

select * from someModel where obj_id in (list)

How I can do it using best Django practices?

P.S. There aren't any relations between two models.

Upvotes: 0

Views: 94

Answers (2)

Anatoly Strashkevich
Anatoly Strashkevich

Reputation: 1914

This shouldn't be a problem, you can try to use max value from query set of obj_id to generate range for querying and then get latest date from each query:

from django.core.exceptions import ObjectDoesNotExist
    result=[]
biggestID=someModel.objects.latest('obj_id') 
#someModel.objects.all().aggregate(Max('obj_id'))

for i in range(biggestID.obj_id)
   try: 
    val=someModel.objects.filter(obj_id=i).latest('creation_date')
   except ObjectDoesNotExist:
    val=None 
   if val is not None:   
     result.append(val)

You also could try:

someModel.objects.values('obj_id').annotate(creation_date=Max('creation_date'))

I want to point this out, you probably know that, but if you use your obj_id as primary key this won't work, because primary key should be unique.

Upvotes: 0

Prakhar Trivedi
Prakhar Trivedi

Reputation: 8526

Try something like this:

    someModelobject = someModel.objects.order_by('creation_date')
    objList = []
    for data in someModelobject:
        objList.append(data.id)

Thanks.

Upvotes: 1

Related Questions