How can i transmit an objects in list?

32 views
Skip to first unread message

Dominis

unread,
Jun 14, 2012, 2:44:50 AM6/14/12
to django...@googlegroups.com
Hello.
I need a bit help with my code.
I write a function for menu building, which should create a list of objects, for designing it in html code.
Code of function below:
def BuildList(categories):
    list = []
    for category in categories:
        if len(category.childrens.all()):
            list.append(category)
            list.append(BuildList(category.childrens.all()))
        else :
            list.append(category)
    return list
 
I call this function for a list of categories, like this:
list = BuildList(Categories.objects.filter(parent = None))
My function work right, but in list i get not an objects, my values have only name of a categories. I thought it happens couse in my Category model in __unicode__  function i place a 'return self.name', and when i call my categories in function - it return just name. :(
What i should do for get full objects in my list? With full collection of parameters.
I suppose this question is easy, but i just start to learn python and django.
Thx for you time and answers.

Àlex Pérez

unread,
Jun 14, 2012, 3:02:53 AM6/14/12
to django...@googlegroups.com
Hello, 


Are you sure?

I suppose that "childrens" is a custom manager, can you show us, the implementation of that manager?

Only for performance "if len(category.childrens.all()):" -> "if category.childrens.exist():"

But your problem, it's rare. Print the type of the firs element of the result list:

list = BuildList(Categories.objects.filter(parent = None))
print type(list[0])

2012/6/14 Dominis <Domi...@yandex.ru>

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



--
Alex Perez
alex....@bebabum.com
 
 bebabum be successful

c/ Còrsega 301-303, Àtic 2
08008 Barcelona
http://www.bebabum.com
http://www.facebook.com/bebabum
http://twitter.com/bebabum

This message is intended exclusively for its addressee and may contain
information that is confidential and protected by professional privilege. 
If you are not the intended recipient you are hereby notified that any 
dissemination, copy or disclosure of this communication is strictly prohibited by law.

Este mensaje se dirige exclusivamente a su destinatario y puede contener
información privilegiada o confidencial. Si no es vd. el destinatario indicado,
queda notificado que la utilización, divulgación y/o copia sin autorización 
está prohibida en virtud de la legislación vigente.

Le informamos que los datos personales que facilite/ha facilitado pasarán a
formar parte de un fichero responsabilidad de bebabum, S.L. y que tiene 
por finalidad gestionar las relaciones con usted. 
Tiene derecho al acceso, rectificación cancelación y oposición en nuestra
oficina ubicada en c/ Còrsega 301-303, Àtic 2 de Barcelona o a la dirección de e-mail lo...@bebabum.com

Dominis

unread,
Jun 14, 2012, 3:36:36 AM6/14/12
to django...@googlegroups.com
I suppose that "childrens" is a custom manager, can you show us, the implementation of that manager?
Childrens it's just a related_items parameter for a field.
This code from models.py
class Categories(models.Model):
    name = models.CharField(max_length=50)
    path = models.SlugField(max_length=50)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='childrens')
    order = models.IntegerField(default=1)
    isShow = models.BooleanField(default=True)
 
By using category.childrens.all() i just check are child items exists...  (any object have this category like 'parent')

Only for performance "if len(category.childrens.all()):" -> "if category.childrens.exist():"
Thx, for advice.
 
But your problem, it's rare. Print the type of the firs element of the result list:
Type is a "class Category". So it's realy object... Now i understand so i wrong with identify my problem.

I want to build HTML through the custom tag, and i cant get access for fields parametrs in custom tag script. In begin i suppose the problem appear when i put objects in list. But type(list[0]) show thet in list i have still object. I check in my template by {{item.field}} - it is show me right data, so in template i sill can get access for fields of an object. But when in my template i call my template tag, in template_tag code i can't get access for fields... code is below.
In my template i do
{% load menu_builder %}
{{ list|BuildMenu }}

In menu_builder.py i have this code:
def BuildMenu(list):
    html = ''
    for item in list:
        print item.path
    return html
it's isnt realy function - just check... but i get a exception
'list' object has no attribute 'path'
Exception Location: ..\templatetags\menu_builder.py in BuildMenu, line 7

Can you help with it? Where i make a wrong?
 

huseyin yilmaz

unread,
Jun 14, 2012, 4:28:50 AM6/14/12
to django...@googlegroups.com
You are probably getting this error because when you generate your list from categories. you are adding sub categories as list. so your list will be like following

[cat1,cat2,cat3,[subcat1,subcat2],[subcat3,subcat4]]

I think you want to use

list.extend(BuildList(category.childrens.all()))
so you will have a one flat list.


list.append(category) repeated twice itlookslike to me that you don't actualy need an if statement here.

def BuildList(categories):
    list = []
    for category in categories:
            list.append(category)
            list.extend(BuildList(category.childrens.all()))
    return list

this method would run same queries.
,

You have a for template tag in django . You can use it instead of your custom filter.


this is great for categories. this is good for keeping trees in relational databases. when you query sub trees, it will do exactly one query every time.
and there is a generic category app too if you need.


I hope that helps.

Dominis

unread,
Jun 14, 2012, 6:48:28 AM6/14/12
to django...@googlegroups.com
You are probably getting this error because when you generate your list from categories. you are adding sub categories as list. so your list will be like following

[cat1,cat2,cat3,[subcat1,subcat2],[subcat3,subcat4]]
Yes, mistake was here. Now i solve it with check "if type(item) is list:"
Using one flat list can't help me, couse i need to build tree with few levels.


this is great for categories. this is good for keeping trees in relational databases. when you query sub trees, it will do exactly one query every time.
and there is a generic category app too if you need.


I hope that helps.

Thx for advice. I will look over it. But i write my custom template for learning and understanding django+python. Couse using ready apps cant let me do it :)

All my questions are answered, so thanks for help!

God bless friendliness community :)
Reply all
Reply to author
Forward
0 new messages