我知道它在某个地方,但我找不到它。
所以我有一个“类别”模型和一个“类别”的“书籍”模型。在模型中创建一本新书时,所有类别都会呈现给用户以分配给该书。在那种情况下,我只希望当前用户创建的类别显示在该字段中,而不是所有类别。
什么是最好的方法?
最佳答案
假设你的模型是这样的:
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
属性。
您的看法:
#GET request
book_form = BookForm(user=request.user)
#POST request
book_form = BookForm(data=request.POST, user=request.user)
关于Django,过滤当前登录用户以多对多模型形式呈现的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16137736/