python - django - get the latest one if duplicate, if not, take it -


i trying achieve this:

i have 2 tables: location , rate. location can have multiple rates. want is, in database , take rate if no duplicate foreignkey, if duplicate, take latest rate.

say, search rate 3, goes db , sees 1 location having rate 3, takes it. location having 2 different rates, 3 , 5. evaluate last one, 5 , don't take since 3!=5

locations = location.objects.filter(???)???? <----- 

how can write in query?

you can use raw queries suppose models are:

class location(models.model):     name = models.charfield(max_length=20)  class rate(models.model):     value = models.integerfield()     location = models.foreignkey('location') 

then use raw query (hope did not confused sql, can play more yourself)

query = ''' select l1.* core_rate r1,core_location l1 l1.id = r1.location_id , value=%s , not exists (select * core_rate r2 r2.location_id = r1.location_id , r2.id > r1.id) ''' value = 3 # or want location.raw(query,value) 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -