问题描述
我知道它在某个地方,但是找不到.
I know it's there somewhere but I can't find it.
因此,我有一个类别"模型和一个书籍"模型,其中有许多到类别".当以模型形式创建新书时,所有类别都将显示给用户以分配给该书.在那种情况下,我只希望当前用户创建的类别显示在该字段中,而不是所有类别.
So I have a 'category' model and a 'book' model which has a many to many to 'category'. When creating a new book in a modelform, all the categories are presented to the user to assign to the book. In that case I want only the categories created by the current user to show up in that field, not all the categories.
什么是最好的方法?
推荐答案
假设您的模型如下:
class Category(models.Model):
....
creator = models.ForeignKey(User)
class Book(models.Model):
...
categories = models.ManyToManyField(Category)
假设您的表单如下:
class BookForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
current_user = kwargs.pop('user')
super(BookForm, self).__init__(*args, **kwargs)
self.fields['categories'].queryset = Categories.objects.filter(creator=current_user)
因此,您需要覆盖表单的__init__
,将当前用户传递给此表单.然后在所需的ManyToManyField上设置queryset
属性.
So, you need to overide __init__
of your form, pass the current user to this form. And then set a queryset
attribute on the ManyToManyField you want.
您的视图:
#GET request
book_form = BookForm(user=request.user)
#POST request
book_form = BookForm(data=request.POST, user=request.user)
这篇关于Django,过滤当前登录用户以多对多模型形式显示的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!