1

i have this model :

class Node(MPTTModel):
    parent              = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children')
    name                = models.TextField(blank=True, null=True)

which have this related model :

class Views(models.Model):
    related_tree = models.ForeignKey(Node, on_delete=models.CASCADE, blank=True, null=True, related_name='related_views')
    views_count = models.PositiveIntegerField(null=True, blank=True, default=0)
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True)
    view_date = models.DateTimeField(default=timezone.now)

What i am trying to do is to order a queryset of the first model by the view date of the second one, this is the view that i have tried :

last_viewed_trees = Node.objects.filter(tree_type='root').order_by('-related_views__view_date')

In that one the result is correct but i have a duplicate view_date of many users. I have tried also this one without success :

        last_viewed_trees = Node.objects.filter(tree_type='root').annotate(time_of_views= Min('related_views__views_count')
        ).order_by('-time_of_views')

        last_viewed_trees = Node.objects.filter(tree_type='root').annotate(time_of_views= Max('related_views__views_count')
        ).order_by('-time_of_views')

Nothing have worked for me, there is something that i am missing, but i cannot identify it.

Farhani Walid
  • 927
  • 1
  • 9
  • 20

0 Answers0