如何从Django中的ModelChoiceField中检索对象id

时间:2015-08-21 12:42:02

标签: django django-models django-forms foreign-keys

这可能是童话般简单的解决方案,但我无法自己解决。所以,基本上我有数据库的经典模型,书籍,作者和出版商。我唯一的问题是书中的问题。要添加书籍,我使用ModelChoiceField选择Publisher。但在尝试保存此表单后,我仍然收到错误“Column'inporter_id'不能为null”。选择字段仅显示发布者的名称,我不知道如何获取此发布者的ID以将其作为发布者的ID添加到此书中。我很感激你的帮助。

models.py:

    class Author(models.Model):
        firstName = models.CharField(max_length=20)
        lastName = models.CharField(max_length=30)

        def __unicode__(self):
            return u'%s %s' % (self.firstName, self.lastName)


    class Publisher(models.Model):
        name = models.CharField(max_length=100)
        year = models.DateField()

        def __unicode__(self):
            return self.name


    class Book(models.Model):
        title = models.CharField(max_length=80)
        publishYear = models.DateField()
        isbnNumber = models.DecimalField(max_digits=13, decimal_places=0)
        author = models.ManyToManyField(Author)
        publisher = models.ForeignKey(Publisher)

forms.py:

class BookForm(forms.ModelForm):
    author = forms.ModelChoiceField(queryset = Author.objects.all())
    publisher = forms.ModelChoiceField(queryset=Publisher.objects.all())

    class Meta:
        model = Book
        fields = ['title', 'isbnNumber', 'publishYear']

view.py:

def book_add(request):
    if request.method == 'POST':
        form = BookForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = BookForm()

    return render(request, 'book_add.html', {'form': form}, context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:2)

author是多对多的,因此您需要使用ModelMultipleChoiceField

但是,我不知道为什么你首先重新定义了这些字段。 ModelChoiceField已经是外键字段的默认值。删除这两个定义,并将authorpublisher添加到fields列表中。