开发者

django ModelMultipleChoiceField queryset/filter for objects already associated

开发者 https://www.devze.com 2023-01-29 02:20 出处:网络
I have a Profile object with manytomany relationship to Category class Profile(models.Model): . . . category = models.ManyToManyField(Category, blank=True)

I have a Profile object with manytomany relationship to Category


class Profile(models.Model):
    . . . 
    category = models.ManyToManyField(Category, blank=True)

In my form, I want to display a checkbox of only the categories associated with the Profile The code below will display all categories.


class ProfileForm(ModelForm):
    . . .
    category = forms.ModelMultipleC开发者_Go百科hoiceField(Category.objects.all(),
                  widget=forms.CheckboxSelectMultiple())

How do i write a queryset so that I show only the categories associated with the Profile? I've variations of this:


    category = forms.ModelMultipleChoiceField(Category.objects.filter(id__in=Profile.category.all()), widget=forms.CheckboxSelectMultiple())

Has this error: 'ReverseManyRelatedObjectsDescriptor' object has no attribute 'all'


woa this was asked 10 years ago..but prolly my idea might prove useful to developers who are will review this. I had a similar challenge.

the simple way is to comment out this:

#category=forms.ModelMultipleChoiceField(
#    Category.objects.filter(id__in=your_profile_instance.category.all()),
#    widget=forms.CheckboxSelectMultiple()
#)

lol and then below, after listing the fields add:

widgets = {
     'category': forms.CheckboxSelectMultiple,
    }

yea....

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method


As far as I know, the relation "category" can only be associated from a Profile instance (giving the associated categories), not from the class Profile itself. That's why you get the error message.

If you substitute Profile in you example with the actual Profile instance (which I read is what you actually try to achieve) it would work better.

category=forms.ModelMultipleChoiceField(
    Category.objects.filter(id__in=your_profile_instance.category.all()),
    widget=forms.CheckboxSelectMultiple()
)

or just

category=forms.ModelMultipleChoiceField(
    queryset=your_profile_instance.category.all()),
    widget=forms.CheckboxSelectMultiple()
)

Have I understood your question correctly?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号