Sunday, April 1, 2012

sorting a list of objects when objects is returning two fields

Hi All

I have a model structure like this :-

class Visit(Model):
    patient                 = models.ForeignKey(Patient)
    ................... and so on ....................
    topics                  = models.ManyToManyField(Topic, limit_choices_to={'reporting':False})
    research_protocol       = models.ManyToManyField(ResearchProtocol,blank=True)
    history_log             = JSONField(blank=True)
   

    ...................and so on .............
    class Meta:
        ordering = ("-date_created",)
  
    def __unicode__(self):
        result = """Visit id:%s pt:%s""" % (self.id, self.patient.id)
        return result

  So the objects looks like this  <Visit: Visit id:24 pt:22>


Now at some table i am making a query that returns me list of objects like this :-

research_obj = ResearchProtocol.objects.get(id=id)
# You can see research_protocol is ManyToManyField in the above model.
visit_ids = research_obj.visit_set.all()

[<Visit: Visit id:34 pt:1> <Visit: Visit id:26 pt:22>,<Visit: Visit id:25 pt:1> <Visit: Visit id:28 pt:22>, <Visit: Visit id:27 pt:22>, <Visit: Visit id:24 pt:1>]

Now i want to sort this list of objects in such a manner that i get this new sorted list :-

[ <Visit: Visit id:24 pt:1>,<Visit: Visit id:25 pt:1> ,<Visit: Visit id:34 pt:1> <Visit: Visit id:26 pt:22>,<Visit: Visit id:27 pt:22>,<Visit: Visit id:28 pt:22> ]

You can see the pt is also getting sorted and Visit Id is also getting sorted .

I am using this :-

ordered_total_visit_ids = sorted(total_visit_ids, key=lambda x: x.patient, reverse=False)

Thanks for help in advance.


--
Regards
Nikhil Verma
+91-958-273-3156

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment