I have two tables like so:
class Collection(models.Model):
name = models.CharField()
class Image(models.Model):
name = models.CharField()
image = models.ImageField()
collection = models.ForeignKey(Collection)
I’d like to retrieve the first image out of every collection. I have attempted:
image_list = Image.objects.order_by('collection.id').distinct('collection.id')
but it didn’t work out the way I expected 🙁
Any ideas?
Thanks.
Don’t use dots to separate fields that span relations in Django; the double-underscore convention is used instead — it means “follow this relation to get to this field”
this is more correct:
However, it probably doesn’t do what you want.
The concept of “first” doesn’t always apply in relational databases the way you seem to be using it. For all of the records in the image table with the same collection id, there is no record which is ‘first’ or ‘last’ — they’re all just records. You could put another field on that table to define a specific order, or you could order by id, or alphabetically by name, but none of those will happen by default.
What will probably work best for you is to get the list of collections with one query, and then get a single item per collection, in separate queries:
If you want to apply an order to the Images, to define which is ‘first’, then modify it like this:
You could also write raw SQL — MySQL aggregation has the interesting property that fields which are not aggregated over can still appear in the final output, and essentially take a random value from the set of matching records. Something like this might work:
This query should get you one image from each collection, but you will have no control over which one is returned.