| 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}] |