Code

Ticket #19842: annotate_values_solution.patch

File annotate_values_solution.patch, 2.3 KB (added by avani9330@…, 6 months ago)

Patch

  • docs/ref/models/querysets.txt

    diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt
    index 170df97..b50d37e 100644
    a b query spans multiple tables, it's possible to get duplicate results when a 
    398398    ordering by related models. Similarly, when using ``distinct()`` and 
    399399    :meth:`values()` together, be careful when ordering by fields not in the 
    400400    :meth:`values()` call. 
     401     
     402    It will be possible to get distinct values by using the :meth:`annotate` 
     403    and :meth:`values` together replacing :meth:`distinct` 
     404    As a simple example let us consider I needed to get a list of blog  
     405    objects that had Time objects attached to them that had been updated  
     406    by a specific user(User object attached to them).  
     407    I wanted the list to be ordered by the most recently updated Time object  
     408    (as there are multiple time objects attached to one blog) 
     409    Models:: 
     410        from django.db import models 
     411        from django.contrib import admin 
     412 
     413        class User(models.Model): 
     414            name = models.CharField(max_length=20) 
     415            state = models.CharField(max_length=20)           
     416            def __unicode__(self): 
     417                return self.name 
     418         
     419        class Time(models.Model): 
     420            date_identiyfy = models.IntegerField() 
     421            date = models.DateTimeField(auto_now_add=True) 
     422            def __unicode__(self): 
     423                return u"%s " % self.date 
     424 
     425        class Blog(models.Model): 
     426            title = models.CharField(max_length=20) 
     427            author = models.CharField(max_length=20)                                                          
     428            def __unicode__(self): 
     429                return self.title 
     430 
     431        class Entry(models.Model): 
     432            name=modiels.ForeignKey(User) 
     433            title=models.ForeignKey(Blog) 
     434            date = models.ForeignKey(Time) 
     435     
     436    Here, the expected result can be got by:: 
     437        >>u=get_object_or_404(User,name='User1') 
     438        >>e=Entry.objects.filter(name=u).values('title').annotate(models.Max('date')).order_by('date') 
     439        >>e 
     440        [{'date__max': 2, 'title': 1L}, {'date__max': 5, 'title': 2L}] 
    401441 
    402442On PostgreSQL only, you can pass positional arguments (``*fields``) in order to 
    403443specify the names of fields to which the ``DISTINCT`` should apply. This