【问题标题】:How to fix, limit_choices_to cannot be a ForeignKey in Django?如何解决,limit_choices_to 不能是 Django 中的 ForeignKey?
【发布时间】:2017-10-21 09:42:12
【问题描述】:

我有如下代码片段:

models.py

​​>
class Notebook(models.Model):
    owner = models.ForeignKey(User, on_delete = models.CASCADE)
    name= models.CharField(max_length=50)

class Note(models.Model):
    create_user = models.ForeignKey(User, on_delete = models.CASCADE)
    text=models.CharField(max_length=500)
    notebook=models.ForeignKey(Notebook, on_delete = models.CASCADE, limit_choices_to = {'owner' : create_user})

但我收到一个错误,即 limit_users_to 不能是外键。 我希望用户在写笔记时只选择他们创建的笔记本,但现在用户可以在未设置 limit_choices_to 的情况下选择其他笔记本。 并且笔记本必须是外键。 我能做什么?

【问题讨论】:

  • 在我看来,这个限制应该在表单级别而不是模型中完成。因为它取决于请求(登录用户)。如果ownercreate_user 相同,create_user 也看起来像不必要的字段。
  • 为什么 Note.notebook FK 会指向用户?而不是笔记本?在任何情况下,如果您有两个 FK 指向同一个模型(此处为 User),则指定 FK 的 related_name 属性。见:stackoverflow.com/questions/583327/…
  • @anupsabraham 你能给我举个例子,我怎样才能在表单级别做出这样的限制?
  • @PalashBauri 我现在不明白你的模型。我在想notebook 是你的Notebook 模型的FK,直到roller 发表评论。您需要做更多工作才能让我们回答您的问题。您是否创建了一个表单,用户可以在其中输入这些详细信息?

标签: python django


【解决方案1】:

您必须在创建笔记时在视图中执行此操作

form.py

from .models import Note
from django.forms import ModelForm

class NoteForm(ModelForm):
    class Meta:
       model = Note

view.py

from django.views.generic.edit import CreateView
from .form import NoteForm
from .models import Note, Notebook

class NoteCreateView(CreateView):
    model=Note
    form_class=NoteForm

    def get_form(self, form_class=None):
        form = super(NoteCreateView, self).get_form(form_class)
        # Thats the solution:
        form.fields['notebook'].queryset = Notebook.objects.filter(owner=self.request.user)
        return form

【讨论】:

  • 用户创建的不包含笔记的笔记本的期望行为是什么?这些是否应该出现在列表中?
  • 必须出现在那里,否则您将永远无法向任何笔记本添加注释。这也超出了问题的范围。
  • 从用户的问题中不清楚。你是完全正确的,这是预期的行为。我只是想知道这是否是 Palash Bauri 想要的。否则您的查询集需要更改。我不明白这是怎么超出范围的(但讨论确实超出了范围)。
猜你喜欢
  • 2015-10-13
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多