[Answer]-Django – get the latest one if duplicate, if not, take it

1👍

You can use raw queries for this
Suppose your 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 this raw query (hope I did not confused with the SQL, but you can play more with yourself)

query = '''
select L1.* from core_rate as R1,core_location as L1 where L1.id = R1.location_id and value=%s and not exists (select * from core_rate as R2 where R2.location_id = R1.location_id and R2.id > R1.id)
'''
value = 3 # or anything you want
Location.raw(query,value)
👤eran

Leave a comment