I spent a lot of time with distinct () wondering why it doesn’t work. Then I decided to change order_by ('?') From order to order_by ('name') from the bald and it worked surprisingly well.

Perhaps distinct () when random sorting does not understand what to compare, I am not aware of its principle of operation, but I would like to somehow make it work.

Perhaps there is a substitute for random sorting through order_by ('?') And so that it works well with distinct ().

In general, I need help. Help me please.

Oh, I almost forgot. DB - SQLite, the site itself on Django.

  • The DISTINCT statement in SQL requires sorting. Therefore, to combine you will not work. - Sergey Gornostaev
  • Then I will try to somehow turn the analog of random sorting. Thanks for the info. - Jimmy
  • Why do you need distinct here? Do you have one-to-one multiple copies of the same Article? - andreymal
  • Yes. Created something like "other entries from a category". If an article has several categories, then each one may issue the same article. If there were no duplicates, then I would not put distinct (). - Jimmy

1 answer 1

Well, if distinct () doesn't want to be friends with order_by ('?'), Then order_by itself will make friends with distinct ().

Made some sort of crutch to random sorting, well, or just a replacement.

 def random(): a = ['', '-'] b = ['id', 'date', 'name', 'author', 'slug', 'views'] c = a[randint(0, 1)] + b[randint(0, 5)] return c context = { 'rand_list': Article.objects.order_by(random()).distinct()[:10] } 

If anyone has any suggestions or criticism (what could be simpler than her: D) - write. It will be interesting to know someone's opinion.