Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

mysql - Django distinct group by query on two fields

I have a model which have 2 fields.

class MyModel:
   tcode = Charfield
   created_on = Date field
   #some more fields

now this model can have multiple rows with same tcode, and each row can have different day or same.

e.g.

tcode1, 1/2/2001
tcode2, 1/2/2001
tcode2, 2/2/2001
....etc.

I want to filter query on this model such that tcode and date field combination should be unique. how can I get all those objects.

i was trying to do this

MyModel.objects.all().order_by('tcode').distinct('tcode', 'created_on')

Now you may ask that in case if there are two rows with same data in two fields which one row I want! it doesn't matter to me, any row would work fine.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't think there's one single query that could do this, because there's no mechanism from database to pick random one from duplicates. However, if you only care about those two fields, you could do:

MyModel.objects.order_by('tcode').values('tcode', 'created_on').distinct()

This won't give you complete MyModel objects, but a list of dictionaries that contain all the existing combinations of tcode and created_on.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...