我想在 Test 表的 store_id 列中保存多个商店 id。设计模型在测试表中保存多个商店 id 的最佳方法是什么 模型.py
class Store(models.Model):
store_name = models.CharField(max_length=100, verbose_name="store")
def __unicode__(self):
return '%s' %(self.name)
def __str__(self):
return self.name
class Test(models.Model):
store_id = models.ForeignKey(Store, on_delete=models.CASCADE, db_column='store_id')
def __unicode__(self):
return '%s' %(self.id)
表格.py
class TestForm(ModelForm):
def __init__(self, *args, **kwargs):
self.fields['store_id'] = ModelChoiceField(queryset=Store.objects.all(), widget=SelectMultiple(attrs={'class':'form-control'})
class Meta:
model = Test
fields = ('store_id',)
我想在 Test 表的 store_id 列中保存多个商店 id。
你不能。这是一个本质上模仿
Store
的主键列的字段,因此它只能包含一个这样的值。
ManyToManyField
[Django-doc],这将在链接到 Store
和 Test
之间创建一个 连接表[wiki],因此:
class Store(models.Model):
name = models.CharField(max_length=100, verbose_name='store')
def __str__(self):
return self.name
class Test(models.Model):
stores = models.ManyToManyField(Store)
def __str__(self):
return f'{self.id}'
ModelMultipleChoiceField
[Django-doc]:
class TestForm(ModelForm):
def __init__(self, *args, **kwargs):
self.fields['stores'].widget.attrs.update(class='form-control')
class Meta:
model = Test
fields = ('stores',)
注意:通常不会在
字段中添加后缀…_id
,因为 Django 将自动添加带有ForeignKey
后缀的“孪生”字段。因此应该 是…_id
,而不是store
。store_id
要从下拉列表中保存多个商店 ID 到
Test
表中,您需要切换 store_id
模型中的 Test
字段以使用 ManyToManyField
而不是 ForeignKey
。
像这样更新你的
models.py
:
from django.db import models
class Store(models.Model):
store_name = models.CharField(max_length=100, verbose_name="store")
def __str__(self):
return self.store_name
class Test(models.Model):
store_id = models.ManyToManyField(Store)
def __str__(self):
return f'Test {self.id}'
然后用以下内容更新您的
forms.py
:
from django.forms import ModelForm, ModelMultipleChoiceField, SelectMultiple
from .models import Test, Store
class TestForm(ModelForm):
def __init__(self, *args, **kwargs):
super(TestForm, self).__init__(*args, **kwargs)
self.fields['store_id'] = ModelMultipleChoiceField(
queryset=Store.objects.all(),
widget=SelectMultiple(attrs={'class':'form-control'})
)
class Meta:
model = Test
fields = ('store_id',)
您在模型中同时使用了
__str__
和 __unicode__
方法,这是不必要的,在 Python 3 和支持 Python 3 的 Django 版本中,您应该只为模型定义 __str__
方法。 Python 2 中使用 __unicode__
方法来确保正确处理 non-ASCII
字符的表示。由于 Python 3 默认对字符串使用 Unicode,因此不再需要 __unicode__
。