简体   繁体   English

Django 保存选择值

[英]Django saving choices values

I want to save selected choice in model.我想在模型中保存选定的选项。 And I want to use Select widget for choices.我想使用 Select 小部件进行选择。 I have a model:我有一个模型:

qobj = Model1.objects.all()

CHOICE = (
    (x.id, x.name) for x in qobj
)

class Model2(models.Model):
    choice_field = models.CharField("CHOICE", max_length=77, choices=CHOICE)

And I got error: "Select a valid choice. 5 is not one of the available choices."我收到错误消息:“选择一个有效的选择。5 不是可用的选择之一。” - error when try to save. - 尝试保存时出错。 I was try forms.ModelChoiceField(queryset=qobj) - No Problem, but I can't get Model.get_choice_field_display() .我正在尝试forms.ModelChoiceField(queryset=qobj) - 没问题,但我无法获得Model.get_choice_field_display() May be someone know solving of this problem?可能有人知道解决这个问题吗?

Error is here:错误在这里:

date = MyModel.objects.order_by('date')[0]
name = MyModel.objects.order_by('name')[0]

MyModel.objects.order_by('date') return a QuerySet, if queryset is empty, it has no index '[0]'. MyModel.objects.order_by('date') 返回一个 QuerySet,如果 queryset 为空,则它没有索引 '[0]'。 Try 'first()' instead [0]:尝试 'first()' 代替 [0]:

date = MyModel.objects.order_by('date').first()
name = MyModel.objects.order_by('name').first()

Case MyModel is empty, first return None Docs: https://docs.djangoproject.com/en/1.9/ref/models/querysets/#first案例 MyModel 为空,先返回 None 文档: https ://docs.djangoproject.com/en/1.9/ref/models/querysets/#first

The issue is caused here:问题是在这里引起的:

def preview(request):
    form = MyModelForm()
    date = MyModel.objects.order_by('date')[0]
    name = MyModel.objects.order_by('name')[0]

You are querying objects, sorting and taking the first item.您正在查询对象、排序并获取第一项。 However, if there are no items it is not possible to do this.但是,如果没有项目,则无法执行此操作。 Instead use .first() , eg而是使用.first() ,例如

    date = MyModel.objects.order_by('date').first()
    name = MyModel.objects.order_by('name').first()

This will return the first item, if there is one, or None if not.如果有,这将返回第一项,如果没有,则返回None See the documentation for more info.有关更多信息,请参阅文档 There are also some other examples in this question for alternative ways to handle this. 此问题中还有一些其他示例,可用于处理此问题的替代方法。

However, I would recommend that you do not use this approach .但是,我建议您不要使用这种方法 When you save the new object ( form01.save() ) this returns the newly created object.当您保存新对象 ( form01.save() ) 时,这将返回新创建的对象。 You can then access this directly for your preview.然后,您可以直接访问它以进行预览。 For example:例如:

preview_model = form01.save()

Using MyModel.objects.order_by('date').first() to get the 'latest record' opens you to a race condition when another user edits another object between the .save() and the select.当另一个用户在.save()和选择之间编辑另一个对象时,使用MyModel.objects.order_by('date').first()获取“最新记录”会使您处于竞争条件。

I'm not sure of the purpose of name = MyModel.objects.order_by('name').first() as this is going to return a completely different object to the previous bit (the first object sorted alphabetically ) - and I cannot imagine why you would want that.我不确定name = MyModel.objects.order_by('name').first()的目的,因为这将返回一个与前一位完全不同的对象(按字母顺序排序的第一个对象) - 我不能想象一下你为什么想要那个。 Try something like the following in views.py :views.py尝试类似以下内容:

def form1(request):
    form = MyModelForm()
    if request.method == 'POST':
        form01 = MyModelForm(request.POST, request.FILES)
        if form01.is_valid():
           preview = form01.save()
           date = preview.date
           return render(request, 'WebMamOffice/en/preview.html', {'form': form01, 'date': date, 'name': name})
    return render(request, 'WebMamOffice/en/form1.html', {'form': form})

您的preview()视图假定至少存在MyModel一个实例:您正在访问MyModel.objects.blah[0] ,它仅在[0]处有内容时才有效。

The best way to use ManyToManyField:使用 ManyToManyField 的最佳方法:

class Model2(models.Model):
    choice_field = models.ManyToManyField(to=Model1)

在django中部分解决了这个问题无法保存模型选择选定值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM