6

I am sorting a query on a timefield from a manytomany object but have trouble during pagination.

models.py:

class Validated(models.Model):
    job_id_list = models.ManyToManyField(JobId , related_name='JobId', blank=True)  

class JobId(models.Model):
    user = models.ForeignKey(User, blank=True, null=True, default=None)
    job_time = models.DateTimeField(auto_now_add=True)

views.py:

results_list = Validated.objects.filter(job_id_list__user=request.user).\
               distinct().order_by('-job_id_list__job_time')

My problem is that pagination is messed up and I get duplicates in my pagination output, even when the query output is ok. (other have this problem too)

I tried several solutions but my issue does not get solved as sorting is bases on a field from a many-to-many object order_by('job_id_list__job_time')

I was thinking of a work-around through creating an annotation to my model by the use of a Model.Manager. Inside this annotation, i try to add the job_time which is a result of a function inside the model. In that way, the job_time would be easily accessible:

for i in result_list:
    job_time_from_model = result_list[i].job_time

I would do this as followed but I don't know how to incorporate the %%function logic%% inside the annotation.

Is this even possible in this way or is another approach required?

models.py:

class ValidatedManager(models.Manager):      
    **%%function-logic%%**
    def date(self, user, id):
            xlinkdatabase_validated_object = self.get(id=id)
            job_id_list = xlinkdatabase_validated_object.\
                    job_id_list.all().order_by('-job_time')
            date_added = None
            for item in job_id_list:
                if item.user == user:
                    date_added = item.job_time
                    break
                return date_added

    def get_queryset2(self, user):
        qs = super(XlinkdatabaseValidatedManager, self).\
        get_queryset().annotate(job_date= **%%function-logic%%**, output_field=DateTimeField())
        return qs

views.py:

results_list = xlinkdatabase_validated.objects.get_queryset2(request.user).\
    filter(job_id_list__user=request.user).distinct().order_by('-job_date')
radzia2
  • 339
  • 4
  • 19

0 Answers0