ModelChoiceField。 ID代替名字 [英] ModelChoiceField. ID instead of the name

查看:64
本文介绍了ModelChoiceField。 ID代替名字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

send_option (在视图中)变量中,我的 name 名称为 Send
我想拥有 ID Send

In send_option (in views) variable I have name of Send. I would like to have ID of Send

该怎么做?谢谢

表格:

class SendOrderForm(forms.Form):
   send_option = forms.ModelChoiceField(queryset=Send.objects.all())

Model :

class Send(models.Model):
    name = models.CharField(max_length=50)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    time = models.CharField(max_length=150)

视图:

if request.method == 'POST':
        form = SendOrderForm(request.POST)
        if form.is_valid():
            send_option = form.cleaned_data['send_option']


推荐答案

您可以做的是

if request.method == 'POST':
    form = SendOrderForm(request.POST)
    if form.is_valid():
        send_option = form.cleaned_data['send_option'].id

form.cleaned_data ['s end_option'] 将获取对象,并且通过执行 .pk id c>或 .id

form.cleaned_data['send_option'] would get the object, and you can get its id by doing a .pk or .id

这篇关于ModelChoiceField。 ID代替名字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆