I am trying to write my first django app and am unclear about good ways to deal with many to many relationships with through tables. My app is like a bibliography but with lots of links between entries in the bibliography. For example, I want to store links to all the entries cited by other entries. There are thirteen types of relations between entries that I want to store so I am using a type field in the through table for that. Some greatly simplified code is below. This code is working but it seems to me that in the view, i.e. the index function, that it will hit the database a lot more than is really necessary. I suspect there are much better ways of handling it if only I understood django better hence this question to you. I was looking at annotate but this isn't really aggregation so it doesn't seem like I can use it. Does any one have any helpful advice?
class Resource(models.Model): # entry in the bibliograpy or something related to an entry title = models.CharField(max_length=255) year = models.IntegerField(null=True, blank=True) publisher = models.ForeignKey(Publisher, null=True, blank=True) is_resource = models.BooleanField(default=False) relations = models.ManyToManyField('self', through='ResourceRelationship', symmetrical=False) def __unicode__(self): return self.title def get_container(self): try: cont = ResourceRelationship.objects.get (from_resource=self.id, relationship=ResourceRelationship.IS_PART_OF).to_resource except ResourceRelationship.DoesNotExist: cont = None return cont class ResourceRelationship(models.Model): relationship = models.IntegerField(choices=RELATIONSHIP_CHOICES) from_resource = models.ForeignKey(Resource, related_name='from_resources') to_resource = models.ForeignKey(Resource, related_name='to_resources') order = models.PositiveSmallIntegerField(default=1) def index(request): resource_list = Resource.objects.filter(is_resource=True) for resource in resource_list: container = resource.container = resource.get_container() if container: resource.year = container.year resource.publisher = container.publisher return render_to_response('resources/index.html', {'resource_list': resource_list}) --~--~---------~--~----~------------~-------~--~----~ 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+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---