Dynamically setting the queryset of a ModelMultipleChoiceField to a custom recordset

Posted by Daniel Quinn on Stack Overflow See other posts from Stack Overflow or by Daniel Quinn
Published on 2010-05-17T05:44:15Z Indexed on 2010/05/17 5:50 UTC
Read the original article Hit count: 278

Filed under:
|
|

I've seen all the howtos about how you can set a ModelMultipleChoiceField to use a custom queryset and I've tried them and they work. However, they all use the same paradigm: the queryset is just a filtered list of the same objects.

In my case, I'm trying to get the admin to draw a multiselect form that instead of using usernames as the text portion of the , I'd like to use the name field from my account class.

Here's a breakdown of what I've got:

# models.py
class Account(models.Model):
    name = models.CharField(max_length=128,help_text="A display name that people understand")
    user = models.ForeignKey(User, unique=True) # Tied to the User class in settings.py

class Organisation(models.Model):
    administrators = models.ManyToManyField(User)


# admin.py
from django.forms import ModelMultipleChoiceField
from django.contrib.auth.models import User

class OrganisationAdminForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        from ethico.accounts.models import Account
        self.base_fields["administrators"] = ModelMultipleChoiceField(
            queryset=User.objects.all(),
            required=False
        )
        super(OrganisationAdminForm, self).__init__(*args, **kwargs)

class Meta:
    model = Organisation

This works, however, I want queryset above to draw a selectbox with the Account.name property and the User.id property. This didn't work:

queryset=Account.objects.all().order_by("name").values_list("user","name")

It failed with this error:

'tuple' object has no attribute 'pk'

I figured that this would be easy, but it's turned into hours of dead-ends. Anyone care to shed some light?

© Stack Overflow or respective owner

Related posts about python

Related posts about django