Query set append

106 views
Skip to first unread message

check....@gmail.com

unread,
Dec 1, 2014, 2:07:59 PM12/1/14
to django...@googlegroups.com
Hello 

I am very new to python and Django . I have a basic question :

1. I have three database tables : Table A , Table B and Table C
2. in my views.py i do :
  • tableB_QuerySet = models.TableB.objects.filter(table_ID = <some value>)
  • This returns 4 rows from table B 
  • Then i iterate over tableB_QuerySet 
                        for x in tableB_QuerySet
                            tableC_QuerySet = models.TableC.objects.filter(tableC_id = x.<fieldname>)
  • I load the temple : template = loader.get_template(>.html>)
  • i use context : context  = RequestContext(request,{ 'tableC_QuerySet': tableC_QuerySet,})
  • return HttpResponse(template.render(context))
3. In my html template i iterate over tableC_QuerySet and print it in a table 


problem is that in my HTML prints only the last entry of  tableC_QuerySet . How do i append all the four entries from table C so that HTML gets all the four entries rather than just the last one 

PS: I cannot change the DB

Thanks in advance 
Appreciate your help



Simon Charette

unread,
Dec 1, 2014, 3:08:36 PM12/1/14
to django...@googlegroups.com
Try using a subquery for this:

tableC_QuerySet = models.TableC.objects.filter(
    tableC_id__in=models.TableB.objects.filter(table_ID = <some value>).values(<fieldname>)
)

Daniel Roseman

unread,
Dec 2, 2014, 7:19:45 AM12/2/14
to django...@googlegroups.com
Well, this is a basic programming issue, and nothing to do with Python or Django.

Each time through your loop, you re-assign `tableC_QuerySet` to a new value. So, naturally, the value that it has at the end of the loop is whatever it had in the last iteration. If you want to get all the elements from each iteration, you'll need to put them into a list. For example:

values = []
for x in tableB_QuerySet:
    values.extend(list(models.TableC.objects.filter(tableC_id = x.<fieldname>)))

In addition, there is almost certainly a more efficient way to do it, rather than doing a separate query for each tableB item, but without seeing more details of your models it's impossible to help further.
--
DR.

Florian Schweikert

unread,
Dec 2, 2014, 7:40:29 AM12/2/14
to django...@googlegroups.com
On 2014-12-01 20:07, check....@gmail.com wrote:
> * I load the temple : template = loader.get_template(>.html>)
> * i use context : context = RequestContext(request,{
> 'tableC_QuerySet': tableC_QuerySet,})
> * return HttpResponse(template.render(context))

you may also have a look at the render shortcut:
https://docs.djangoproject.com/en/1.7/topics/http/shortcuts/#render

-- Florian

check....@gmail.com

unread,
Dec 2, 2014, 8:31:23 PM12/2/14
to django...@googlegroups.com
Thanks guys . Appreciate the help !!
Reply all
Reply to author
Forward
0 new messages