Я попытался написать Object.assignDeep
, который основан на пополнении Object.assign
на mdn .
(ES5)
Object.assignDeep = function (target, varArgs) { // .length of function is 2
'use strict';
if (target == null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource != null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
if (typeof to[nextKey] === 'object'
&& to[nextKey]
&& typeof nextSource[nextKey] === 'object'
&& nextSource[nextKey]) {
Object.assignDeep(to[nextKey], nextSource[nextKey]);
} else {
to[nextKey] = nextSource[nextKey];
}
}
}
}
}
return to;
};
console.log(Object.assignDeep({},{a:{b:{c:1,d:1}}},{a:{b:{c:2,e:2}}}))
См. ModelChoiceField . Вы должны установить empty_label в None. Таким образом, ваш код будет выглядеть примерно так:
class BookSubmitForm(ModelForm):
library = ModelChoiceField(queryset=Library.objects, empty_label=None)
class Meta:
model = Book
EDIT: изменил имя поля на нижний регистр
self.fields['xxx'].empty_label = None
не работает Если тип поля - TypedChoiceField
, у которого нет свойства empty_label
. Что мы должны сделать, так это удалить первый выбор:
class BookSubmitForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BookSubmitForm, self).__init__(*args, **kwargs)
for field_name in self.fields:
field = self.fields.get(field_name)
if field and isinstance(field , forms.TypedChoiceField):
field.choices = field.choices[1:]
Если вы укажете blank=False
и default=<VALUE>
в определении поля модели, то Django по умолчанию не сделает пустой выбор; обратите внимание, что значение по умолчанию может быть неверным выбором и, например, установить на ''
или любой invalid choice
.
class Book(models.Model):
library = models.ForeignKey(Library, null=False, blank=False, default='')
...
Если вы используете ModelForm, вам не нужно указывать запрос, требуемый, ярлык и т. д. Но для ответа на повторный вызов вам нужно сделать это снова.
Фактически вы можете сделать это, чтобы избежать повторного -выполнение всех
class BookSubmitForm(ModelForm):
def __init__(self, *args, **kwargs):
super(BookSubmitForm, self).__init__(*args, **kwargs)
self.fields['library'].empty_label = None
class Meta:
model = Book
self.fields['library'].empty_label = None
, если вы не собираетесь менять запрос. – guival 14 December 2017 в 12:44