How do I make such a thing. There is an activity class, there is an occupation class (lesson). Each activity has a type and date. The number of types is certainly small. I need to sort objects of type occupation by date of activity of a particular type. I can not figure out how to do it. Is it possible to stir up something like this:

Leson.objects.filter(action__type="w").order_by(action__type="w", "-action__date").distinct() 

But of course it will not work. And how to write so that it works?

Update : The idea is that I first filter by activity, and then I want to sort by activity date. The problem is that you need to sort by activity of a particular type. For example, I filtered the objects. I got the following

Object A has fields

 активность { тип: "w", дата 11-01-01 } активность { тип: "g", дата 11-04-07 } активность { тип: "r", дата 11-03-06 } .... 

Object B has fields

 активность { тип: "w", дата 11-10-01 } активность { тип: "r", дата 11-03-03 } .... 

That is, only those objects that have activities like "w" remain. And the question is, how now to sort them by the date of activity type "w"? If you simply write order_by("-action__date") , then it will sort by all the activities of this object, and I need to take into account only a certain type.

If you select objects in an array, and then manually sort, the idea is not the best, there are a lot of objects, and there are many activities for each object.

Update 2 :

 class Lesson(BaseModel): __metaclass__ = LessonMetaClass ... # Еще много полей class Action(BaseModel): lesson = models.ForeignKey('Lesson', null=True, related_name="actions") type = models.CharField(max_length=32) date = models.DateTimeField(default=datetime.datetime.now) 

On exit, I want to get a sorted QuerySet .

    3 answers 3

    What does "by date of activity of a certain type" mean? If you have an iterable collection, you can sort it with the sorted function (there is a sort method for lists). Draw a function that sets the order and forward. For example:

     def mycmp(o1, o2): if(o1.activity == o2.activity): return cmp(o1.date, o2.date) else: return cmp(o1.activity, o2.activity) a=sorted(lessons, mycmp) 

    This is a bit not what is necessary according to the condition of the problem, but it (this condition) is incomprehensible. It would be desirable to explain the initial condition.

    • Updated the question. - Nicolas Chabanovsky

    Honestly, it's not at all clear what you want to filter or sort.

    it is necessary to sort objects of type occupation by the date of activity of a certain type.

    if you need lessons only of this type sorted by activity date, then in theory you should do so

     Leson.objects.filter(action__type="w").order_by("-action__date").distinct() 

    if you need all the lessons sorted by type and date of activity, then

     Leson.objects.all().order_by("action__type", "-action__date").distinct() 

    if something else is needed, explain what it is.

    As far as I understood from updating one lesson there are several activities, in fact what the snag is, only I did not understand how they relate. I think the model code would clarify everything. It is possible that you will have to filter and sort the activities, and then get lessons from these activities (again, if I understood correctly). Those. sort of

     Lesson.objects.filter(activity__in=Activity.objects.filter(type="w").order_by('-date')) 

    Update

    At the moment, only this option comes to my mind:

     lessons = [] for active in Active.objects.filter(type='w').order_by('-date'): lessons.append(active.lesson) 

    Update 2

    Then you need to look at raw sql queries :

     lessons = Lesson.objects.raw("""SELECT DISTINCT <you fields> FROM youapp_lesson AS l INNER JOIN youapp_active AS a ON a.lesson_id = l.id WHERE a.type='w' ORDER BY a.date DESC""") 

    PS By the way, it is still very good to see what a regular ORM request forms. It helps to determine in which direction and how to move.

    • It's not gonna go. As you wrote we will sort the activity. When we retrieve the questions, they will be in the order of the questions. Tested by experience, even before asking a question. - Nicolas Chabanovsky
    • Nevertheless, show the code of your models. Perhaps what you want can be done in a different way - ChehoV
    • Again, you are proposing to create an array. Not okay. I have a multistage filter. Yes, and too many objects. - Nicolas Chabanovsky
    • one
      Tell me, have you found a suitable solution? - ChehoV
    • Unfortunately, I have postponed the task for now, because I have not found a solution. - Nicolas Chabanovsky

    maybe my experience will help you in something like this: I had to add a lot of sorting filters that can sometimes be "empty", using regexps I managed to reproduce everything I need

    Additionally, I used django-sorting, django-pagination (they can be found on the git hub) part of the code from views:

     if request.GET.get('phone'): phone = request.GET.get('phone') else : phone = r'^[0-9]' if request.GET.get('poz'): poz = request.GET.get('poz') else : poz = r'^[0-9]' acc = accounts.objects.filter(name__regex=poz).filter(account__regex=phone).exclude(status=9) 

    django-sorting is highly customizable.

    Threat if you got a QuerySet and then want to do something with it, then this is also not a problem:

     >>> acc = accounts.objects.all() >>> acc [<accounts: 80>, <accounts: 50000000>, <accounts: 093333335>, '...(remaining elements truncated)...'] >>> acc.exclude(status=9) [<accounts: 50363230>, <accounts: 09339123115>, <accounts: 80>, <accounts: 8505023138196>, '...(remaining elements truncated)...'] >>> acc.filter(id=4) [<accounts: 80>] 

    that is, you can sort those that have activities like "w", and then separately filter as you like: something like

     type_w = Leson.objects.filter(action__type="w") type_w.order_by("-action__date")