On Mar 22, 12:19 pm, James <[email protected]> wrote:
> Hi,
>
> I am struggling to get a piece of code working.
> I've looked at it too much and now can't see what im doing wrong.
>
> Anyone have any ideas? The error is as follows:
> Type Error
> string indices must be integers - (if ids['m'['manufacturer__id']]
"'m'['manufacturer__id']" is trying to to an index lookup on string
"'m'" using string "'manufacturer__id'" as index - which can't work,
since strings can (of course) only be indexed by integers
> is
> not m['manufacturer__id']: )
> Code:
>
> tmp_manufacturers = Product.objects.filter(category=category).values(
> 'manufacturer__title', 'manufacturer__slug',
> 'manufacturer__id'
> ).distinct()
>
> manufacturers = {}
> for m in tmp_manufacturers:
> ids = {}
>
> if ids['m'['manufacturer__title']] is not
> m['manufacturer__title']:
First error is the use of quotes around "m" - this should read
"ids[m['manufacturer__title']]".
Now there are two other errors in this line:
1/ you should NOT use the identity operator to test for equality -
IOW, you want to replace 'is' with '==' (or, in this case, 'is not'
with '!=')
2/ if the 'ids' dict doesn't yet have a value set for
m['manufacturer__title'], you'll get a KeyError.
> ids.append(m['manufacturer__title'])
Looks like you're confusing dicts with lists.... dicts don't have an
"append" method.
> manufacturers.append({
> 'title': m['manufacturer__title'],
> 'slug': m['manufacturer__slug'],
> 'id': m['manufacturer__id'],
> 'total_products': Product.objects.filter(
> category=category,
> manufacturer__slug=m['manufacturer__slug']
> ).count()
> })
I don't know what your models looks like, but there's something wrong
IMHO - if there's to be a one2many or many2many relationship between
Products and Manufacturer, then it would better be explicit (using a
Model.ForeignKey or Model.ManyToManyField), and done on the
manufacturer *id*, not on the slug. This may also save you (and your
computer) some useless work...
> Also, does anyone have any decent documentation on arrays?
Arrays ??? This is not PHP, this is Python. Look for "list" and "dict"
in the FineManual (I mean, the fine *Python* manual). FWIW, do
yourself a favour and learn Python - at least do the official intro
tutorial. You just can't hope to do anything good in Django if you
don't know at least the most basic Python builtin types and operators.
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.