我的应用(示例)使用html表单来获取用户输入。然后我使用此输入来搜索数据库表中的匹配项。然后,我想打印匹配数据库列中每一行的结果。
Models.py
...
class Method(models.Model):
method_name = models.CharField(max_length=50)
method_description = models.TextField(max_length=100, blank=True, null=True)
def __unicode__(self): #python 3.3 __str__
return self.method_name
class Meta:
ordering = ['method_name']
class Project(models.Model):
project_name = models.CharField(max_length=50)
project_description = models.TextField(max_length=100)
contact_person = models.ForeignKey(Contact)
def __unicode__(self):
return self.project_name
class Meta:
ordering = ['project_name']
class Sample(models.Model):
sample_ID = models.CharField(max_length=20)
sample_name = models.CharField(max_length=30)
date = models.DateField()
project = models.ManyToManyField(Project)
method = models.ForeignKey(Method)
def __unicode__(self):
return self.sample_ID
class Meta:
ordering = ['sample_ID']
views.py
def sample_lookup(request):
form = SampleLookupForm(request.POST or None)
id = ''
results = []
errors = False
catresults = ()
categories = ['Sample Name', 'Date', 'Project', 'Method']
if form.is_valid():
id = form.cleaned_data['Sample_ID'].upper()
# Iterate through all sample IDs and check.
# Not efficient for large query sets.
for s in Sample.objects.all():
if s.sample_ID == id:
results = [s.sample_name, s.extraction_date, s.project, s.method]
catresults = zip(categories, results)
errors = False
break
if not results:
errors = True
context = {
"errors": errors, "catresults": catresults,
"q": id, "form": form,
}
return render(request, 'sample_lookup.html', context)
(我知道这种观点非常丑陋但现在仍有效。)
在此之后,我使用
在html中打印出来{% for result in catresults %}
<!-- Field = result.0, value = result.1 -->
查询本身就是样本ID。我在Sample的所有列中搜索匹配的ID。当/如果匹配时,我打印该列的每个字段。对于CharField,DateField和ForeignKey字段,我得到一个匹配该样本信息的漂亮字符串。
但是,对于ManyToManyField,我得到samples.Project.None。
Field Value
Sample_Name Sample_A
Date 2.2.15
Project samples.Project.None
Method A real method
所以看来s.project给出了samples.Project.None。我有一种感觉,这是因为这是一个ManyToMany字段。如何从该字段获得所有结果?
我尝试过s.project.project_name,但是没有用。
django = 1.8 python = 2.7
谢谢