On Jan 17, 8:28 pm, pfwd <pfwdt...@googlemail.com> wrote: > Hi am very new to Django/Python and I need some help with a model > method > > I have two tables Linked by a foreign key and their forms are embedded > in the admin interface. > One table is called Quote and one table is called Task. The task table > has a field called time_taken > In the Quote list I want to display the total amount of time to under > go all the tasks in each quote. > > This is what I'm doing and its just displaying (None) in the list > > class QuoteAdmin(admin.ModelAdmin): > fieldset = [ > (None, {'fields': ['q_number']}) > ] > inlines = [TaskInline] > > list_display = ('q_number', 'total_time','created_date') > > def total_time(self,queryset): > task_objs = self.Task.objects.all() > > total_time = 'No time taken' > > for record in task_objs: > total_time = total_time + record.time_taken > return total_time > > I'm trying to get all the tasks for each quote by doing > self.Task.objects.all() and then looping through them and adding the > time_taken to the var total_time. > > I guess this syntax is just plain wrong or the method is not being > called as its not showing any errors > I have a javascript/PHP background and I would like to learn more > Python > - Please be kind :)
OK a few pointers. * a custom list_display method takes parameters (self, obj), where obj is the object being displayed in that row - here it's an instance of Quote. * 'self.Task' means nothing. You want to get the tasks related to the Quote, which is in 'obj', so you use 'obj.task_set.all()'. With this, your code would work as is. * A nicer way of doing it would be to get the DB to sum the time_taken values. This should work: from django.db.models import Sum return obj.task_set.aggregate(Sum('time_taken')) ['time_taken__sum'] (the square brackets at the end are needed because 'aggregate' returns a dictionary, and we just want the value from there). -- DR.
-- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@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.