Friday, May 3, 2013

Re: list comprehension query

On Fri, May 3, 2013 at 2:32 PM, MikeKJ <mike.jones@paston.co.uk> wrote:
> I am using enumerate to find the position in a list but it doesnt seem to be
> working or throwing an error any ideas please?

"Not working" is not a very good description of what is going wrong.
If it did throw an error, not including it is also a bit of a pain..

>
> def detail(request, item_id):
> item = Item.objects.get(pk=item_id)
> list = []

You shouldn't use keywords like 'list' or 'dict' as variable names, it
(eventually) causes hard to solve issues.

> count = Item.objects.all().count()
> all = Item.objects.all()
> for y in all:
> list.append(y.id)

This whole section is better written:

item_list = list(Item.objects.all().values_list('id', flat=True))
count = len(item_list)

> get = (i for i,x in enumerate(list) if x==item_id)

First of all, item_id is probably at this point a string - it's come
from the URL, right?

item_id = int(item_id)

If you do list comprehensions with '()' you end up with a generator
function. If you do it with '[]', you get a proper list comprehension:

idx_list = [ idx for idx, list_item_id in enumerate(item_list) if
item_id == list_item_id ]

However, you are searching a list for a specific value, and all the
values in the list are distinct:

idx = item_list.index(item_id)

> for i in get:
> raise NameError(i)
> if i > 0:
> previous = list[i - 1]
> if i < (count-1):
> next = list[i + 1]
> return render_to_response('news/item_detail.html',{ 'item': item,},
> context_instance=RequestContext(request))
>
> cheers

The rest should work, apart from the (deliberate?) NameError, and the
fact that you have the index of your current item in your list in a
single variable.

This is not a particularly efficient way of finding the previous and
next items. I would simply hit the DB twice, rather than load every
item id into an array and search it:

previous = None
next = None
try:
previous = Item.objects.filter(pk__lt=item_id)[0:1].get()
except Item.DoesNotExist:
pass
try:
next = Item.objects.filter(pk__gt=item_id)[0:1].get()
except Item.DoesNotExist:
pass

Cheers

Tom

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate