Django: combining different requests into the same model

I program search by model and I have a problem.

My model is almost like this:

class Serials(models.Model):
    id = models.AutoField(primary_key=True)
    code = models.CharField("Code", max_length=50)
    name = models.CharField("Name", max_length=2000)

and I have a database in tuples, like these:

1   BOSTON   The new Boston
2   NYT      New York journal
3   NEWTON   The old journal of Mass
4   ANEWVIEW The view of the young people

If I search for a string new, then I want:

  • first names, beginning with the string
  • then codesstarting at line
  • then nameswhich contains the string
  • then codeswhich contains the string

So, the previous list should look like this:

2   NYT      New York journal
3   NEWTON   The old journal of Mass
1   BOSTON   The new Boston
4   ANEWVIEW The view of the young people

The only way I found such a result is to do different searches (if I put β€œOR” in the same search, I will lose the order I want).

, , , , , , 4 . , !

, , , 4 .

+2
2

, :

result = itertools.chain(qs1, qs2, qs3, qs4)

, .

sql, raw sql, :

Serials.objects.raw(sql_string)

:

2 Django?

+7

qs1 | qs2 | qs3 | qs4. .

Q() objects:

from django.db.models import Q
value = "new"
Serials.objects.filter(Q(name__startswith=value) |
                       Q(code__startswith=value) |
                       Q(name__contains=value) |
                       Q(code__contains=value).distinct()

, , , db, .

, qs1 | qs2, , db. ( , ).

+5

Source: https://habr.com/ru/post/1536787/


All Articles