使用django在mysql数据库上使用DISTINCT

Nei*_*man 1 python mysql django distinct

我一直在尝试(并且失败)生成一个查询,该查询省略了模型的结果,而不必创建第二个数据库.

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")
Run Code Online (Sandbox Code Playgroud)

这是模型布局.我想要得到的是boss字段中所有内容的列表,但是省略了重复项.

我尝试过各种不同的方法,.value_list,.values,order_by.().distinct等等,但似乎没什么用.

使用以下内容

bosses = LootTable.objects.values('boss').distinct()
Run Code Online (Sandbox Code Playgroud)

返回

[{'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)...']
Run Code Online (Sandbox Code Playgroud)

从结果中可以看出它返回了重复项.

ptr*_*ptr 5

你真的应该花点时间把你的模型类的相关部分放在问题中.像你一样冷凝它可能看起来像在现实中节省时间,这使得更难以准确地计算出你想要做的事情.

根据你所放的,

q = LootTable.objects.values('boss').distinct()
Run Code Online (Sandbox Code Playgroud)

应该工作正常.如果没有,那么其他地方就出现了问题.

顺便说一句,老板不应该只有一个战利品表吗?你为什么还要做distinct?事实上,看看这个模型,如果我明白你要做什么(并且不能保证我这样做!)我可以发现很多可能会让你感到困惑的问题,即:

a)为什么你还有一个LootTable表呢?使用Boss和之间的多对多外键可以实现相同的功能Item.

b)为什么LootTable上同时包含item_id和item_name?为什么不将item作为Item模型的外键?(即正确标准化的数据)

c)如果它只指向一个表怎么样Item?:)