Django Queryset to List conversion => Data loss?
I'm trying to populate a list based on partiular members, but it doesn't seem to be going to plan.
user = request.user
members = []
userprofile = user.get_profile()
if user.is_superuser or user.is_staff:
if userprofile.countries.count() == 0:
members = Member.objects.all()
elif userprofile.countries.count() >0:
for c in userprofile.countries.all():
m1 = Member.objects.filter开发者_C百科(location__country = c)
members.append(m1)
else:
pass
self.fields['members'].choices = [(member.id, member.display_name()) for member in members]
Here, we see self.fields (it's a multi-select box) has member.id. I've tried both this and member.pk, but it doesn't seem to be working => Django informs me member has no attributes called id or pk
If a user is a superuser and has a countries count of 0, then It works fine; So i know its to do with the append function underneath the queryset call.
Could anyone offer any hints as to why id/pk is unavailable/lost after adding the results to a list? In addition, does anyone know of a workaround?
I think your problem is that Member.objects.filter(location__country = c)
is going to return a QuerySet object... which is essentially a hook to execute a query (lazily) once it is evaluated. if you change that to list(Member.objects.filter(location__country = c))
it will be evaluated immediately and give you back a list of Member model instances instead of a QuerySet object.
There are a couple problems with your code. First, Member.objects.filter(location__country=c) returns a queryset. The queryset is not evaluated by being appended to members (see https://docs.djangoproject.com/en/1.3/ref/models/querysets/#when-querysets-are-evaluated). Second, even if you evaluate the queryset as Matthew suggests, members will be a list of lists, instead of a flat list as your code expects. Try this code instead:
if user.is_superuser or user.is_staff:
if not userprofile.countries.count():
members = Member.objects.all()
else:
members = Member.objects.filter(location__country__in=userprofile.countries.all())
精彩评论