Django将默认值保存在代理模型中 [英] Django save default value in Proxy Model
问题描述
不同的代理模型的类型应该不同.如果我查询这些模型,我会选择正确的模型.
Different proxy models should be different in type. If I query those models I the right ones.
我正在尝试在代理模型中保存默认类型字段.我不想每次都在视图中设置它.
I am trying to save a default type field in a proxy model. I don't want to set it everytime in the view.
这不起作用.类型字段始终为"TYPE1".
This does not work. The type field is always "TYPE1".
models.py:
models.py:
class MyModel(models.Model):
class ModelType(models.TextChoices):
TYPE1 = 'TYPE1', _('TYPE1')
TYPE2 = 'TYPE2', _('TYPE2')
type = models.CharField(max_length=100, choices=ModelType.choices, default='TYPE1')
class Type2Manager(models.Manager):
def get_queryset(self):
return super(Type2Manager, self).get_queryset().filter(type='TYPE2')
def save(self, *args, **kwargs):
kwargs.update({'type': 'TYPE2'})
return super(Type2Manager, self).save(*args, **kwargs)
class Type2ProxyModel(MyModel):
class Meta:
proxy = True
objects = Type2Manager()
views.py:
def create_type2_model(request):
form = Type2Form(request.POST, initial={})
f = form.save(commit=False)
f.save()
forms.py:
class Type2Form(ModelForm):
class Meta:
model = Type2ProxyModel
更新25.02.2020 12:18:
Update 25.02.2020 12:18:
我发现这设置了正确的类型.但是我不知道如何在ModelForm中使用create().
I found out that this sets the correct type. But I don't know how to use create() in a ModelForm.
class Type2Manager(models.Manager):
...
def create(self, **kwargs):
kwargs.update({'type': 'TYPE2'})
return super(Type2Manager, self).create(**kwargs)
Type2ProxyModel.objects.create()
推荐答案
模型管理器在表级"上运行.当您通过表单创建对象时,它使用模型对象而不是模型管理器,因此您需要覆盖代理模型的 save
.如果我将您的 Type2ProxyModel
修改为此,则会起作用:
A model manager operates on a "table-level". When you create an object via a form it uses the model objects and not the model manager and thus you'd need to override the save
of your proxy model. If I modify your Type2ProxyModel
to this it works:
class Type2ProxyModel(MyModel):
class Meta:
proxy = True
objects = Type2Manager()
def save(self, *args, **kwargs):
self.type = 'TYPE2'
return super(Type2ProxyModel, self).save(*args, **kwargs)
这篇关于Django将默认值保存在代理模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!