我的 Django 应用程序中有两个模型,用于存储用于某些同源搜索程序的搜索参数:
# models.py
class Search(models.Model):
"""A class to represent search runs."""
program = models.CharField(max_length=20)
results_file = models.FileField(
upload_to=(SEARCH_RESULTS_DIR)
)
timestamp = models.DateTimeField()
def __unicode__(self):
return u'%s %s' % (self.program, self.timestamp)
class FastaRun(models.Model):
search = models.OneToOneField('Search', primary_key=True)
# the user-input FASTA formatted protein sequence
query_seq = models.TextField()
# -b "Number of sequence scores to be shown on output."
number_sequences = models.PositiveIntegerField(blank=True)
# -E "Limit the number of scores and alignments shown based on the
# expected number of scores." Overrides the expectation value.
highest_e_value = models.FloatField(default=10.0,
blank=True)
# -F "Limit the number of scores and alignments shown based on the
# expected number of scores." Sets the highest E-value shown.
lowest_e_value = models.FloatField(blank=True)
mfoptions = [
('P250', 'PAM250'),
('P120', 'PAM120'),
('BL50', 'BLOSUM50'),
('BL62', 'BLOSUM62'),
('BL80', 'BLOSUM80')
]
matrix_file = models.CharField(
max_length=4,
choices=mfoptions,
default='BL50'
)
database_option = models.CharField(
max_length=25,
choices=BLAST_DBS,
default=INITIAL_DB_CHOICE
)
ktupoptions = [(1, 1), (2, 2)]
ktup = models.PositiveIntegerField(
choices=ktupoptions,
default=2,
blank=True
)
注意这里FastaRun
是一种Search
. FastaRun
扩展搜索,因为为 a 定义了更多参数FastaRun
。AFastaRun
必须有一个Search
与之链接的实例,并且该Search
实例是 的主键FastaRun
。
我有一个ModelForm
班级FastaRun
。
# views.py
class FastaForm(forms.ModelForm):
class Meta:
model = models.FastaRun
我有一个视图函数,我需要使用它来填充FastaForm
和保存一个新Search
实例以及FastaRun
基于用户提交的表单的一个新实例。该表单不包括选择Search
实例的选项。这是不可能的,因为该Search
实例只有在用户实际提交此搜索后才能存在。
以下是该函数需要执行的操作的概述:
# also in views.py
def fasta(request, ...):
# populate a FastaForm from the information POSTed by the user--but
# how to do this when there's no Search information coming in from
# the user's request. We need to create that Search instance, too,
# but we also have to...
# validate the FastaForm
# ... before we can ...
# create a Search instance and save() it
# use this saved Search instance and give it to the FastaForm [how?]
# save() the FastaForm [save the world]
pass
因为Search
and FastaRun
(and因此FastaForm
) 交织在一起,我觉得我正在进入 Catch-22。我需要保存一个Search
实例,其参数存储在 POST 请求中,但必须使用FastaForm
's 验证来验证其参数。但是,我认为在FastaForm
实例化实例之前无法实例化Search
。Search
然而,在我使用...验证之前,我无法实例化
实例FastaForm
。你明白了。
我在这里想念什么?必须有一种相当干净的方法来做到这一点,但我看不清楚。
另外,如果我错了,请纠正我,但是只要模型之间存在某种关系(例如,还有 forForeignKey
和ManyToMany
字段),就可能发生同样的依赖情况。因此,肯定有人想到了这一点。