ModelChoiceField. ID instead of the name

2020-07-18 09:20发布

问题:

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

How to do it? Thanks

Form:

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)

Views:

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

回答1:

What you can do is,

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

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



回答2:

Does your Send model has __unicode__ or __str__ method that returns name of the instance?

If so, you need to return id of instance rather than name.



标签: django