Using DISTINCT on mysql database with django

distinct, django, mysql, python

Solution

You really should take the time to put the relevant pats of your model class in the question. Condensing it like you have may seem like saving time bit in reality it makes it harder to work out exactly what you're trying to do.

Based on what you have put,

q = LootTable.objects.values('boss').distinct()

should work fine. If it doesn't then something else is wrong somewhere.

As an aside, shouldn't a boss only have one loot table? Why do you need to do `distinct` anyway? In fact looking at the model, if I understand what you're trying to do (And there is no guarantee that I do!) I can spot quite a few issues that may bite you down the line, namely:

a) why do you have a LootTable table anyway? The same functionality could be achieved with a many-to-many foreign key between `Boss` and `Item`.

b) Why does the LootTable have both item_id and item_name on it? why not just have item be a foreign key to the `Item` model? (i.e. properly normalised data)

c) how is it a table if it only points to one `Item`? :)

Problem

I've been trying (and failing) to generate a query that omits results from a model without having to make a second database. ``` pmrs.models.LootTable class LootTable(models.Model): boss = models.CharField(max_length=255) itemid = models.IntegerField() itemname = models.CharField(max_length=255) wfflag = models.BooleanField(help_text="Set true if warforged") ``` That's the model layout. What I'm trying to get is a list of everything in the boss field, but then omit the duplicates. I've tried various different ways, .value_list, .values, order_by.().distinct etc. but nothing seems to work. Using the following ``` bosses = LootTable.objects.values('boss').distinct() ``` Returns ``` [{'boss': u'Thok the Bloodthirsty'}, {'boss': u'Ordos'}, {'boss': u'Paragons of the Klaxxi'}, {'boss': u'Ordos'}, {'boss': u'Spoils of Pandaria'}, {'boss': u'Spoils of Pandaria'}, {'boss': u'Galakras'}, {'boss': u'General Nazgrim'}, {'boss': u'Ordos'}, {'boss': u'Spoils of Pandaria'}, {'boss': u'Siegecrafter Blackfuse'}, '...(remaining elements truncated)...'] ``` As you can see from the results it's returning duplicates.

Original source