我正在为拥有多个地点的公司创建在线求职申请。我想允许申请人能够选择代表他们想申请的每个商店的复选框(可能是多个)。我为了扩展性目的而对这些硬编码犹豫不决,所以我希望创建2个模型(我有更多,但是对于这个例子,这些只是相关的2个):
申请人
class Applicant(models.Model):
name = models.CharField(max_length=200)
city = models.CharField(max_length=200)
state = models.CharField(max_length=200)
zip = models.CharField(max_length=200)
social_security_number = models.CharField(max_length=200)
phone = models.CharField(max_length=200)
alt_phone = models.CharField(max_length=200, blank=True)
us_citizen = models.BooleanField()
committed_felony = models.BooleanField()
is_16 = models.BooleanField()
has_drivers_license = models.BooleanField()
is_disabled = models.BooleanField()
prev_employed = models.BooleanField()
felony_explanation = models.TextField(blank=True)
disabled_explanation = models.TextField(blank=True)
prev_employment_manager = models.CharField(max_length=200, blank=True)
prev_employment_year = models.CharField(max_length=4, blank=True)
skills = models.TextField()
was_completed = models.BooleanField(default=False)
def __unicode__(self):
return self.name
商品
class Store(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=200)
city = models.CharField(max_length=20)
state = models.CharField(max_length=20)
def __unicode__(self):
return self.description
我希望(我认为)在申请者模型中添加一个MultipleChoiceField,它可以从Store的所有实例创建选择(每行一个)。到目前为止,我已在申请人类中尝试过这个:
def get_stores():
self.stores = Store.objects.all()
但无法(据我所知)抓住Store的实例,就像我希望的那样。以下是我的一些问题:
答案 0 :(得分:1)
这似乎是ManyToManyField
的规范用例。
class Store(models.Model):
...
class Applicant(models.Model):
name = models.CharField(max_length=200)
...
was_completed = models.BooleanField(default=False)
stores = ManyToManyField(Store, related_name='applicants')
在字段中显示此表单时,它应自动使用MultipleSelectField
参考:https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/