django ModelMultipleChoiceField 查询集/过滤器已关联的对象
我有一个与类别有很多关系的配置文件对象
class Profile(models.Model):
. . .
category = models.ManyToManyField(Category, blank=True)
在我的表单中,我想仅显示与配置文件关联的类别的复选框 下面的代码将显示所有类别。
class ProfileForm(ModelForm):
. . .
category = forms.ModelMultipleChoiceField(Category.objects.all(),
widget=forms.CheckboxSelectMultiple())
如何编写查询集以便仅显示与配置文件关联的类别? 我有这样的变体:
category = forms.ModelMultipleChoiceField(Category.objects.filter(id__in=Profile.category.all()), widget=forms.CheckboxSelectMultiple())
有这个错误:'ReverseManyRelatedObjectsDescriptor'对象没有属性'all'
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.ModelMultipleChoiceField(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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
哇,这是 10 年前提出的问题……但我的想法可能对那些会审查这个的开发人员有用。我也遇到过类似的挑战。
简单的方法是注释掉这一点:
哈哈,然后在下面列出字段后添加:
yea....
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method
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:
lol and then below, after listing the fields add:
yea....
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method
据我所知,关系“类别”只能与 Profile 实例关联(给出关联的类别),而不能与类 Profile 本身关联。这就是您收到错误消息的原因。
如果您将示例中的 Profile 替换为实际的 Profile 实例(我读到的是您实际尝试实现的目标),那么效果会更好。
或者只是
我正确理解了你的问题吗?
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.
or just
Have I understood your question correctly?