2 python django syntax many-to-many
模型:
class Pathology(models.Model):
pathology = models.CharField(max_length=100)
class Publication(models.Model):
pubtitle = models.TextField()
class Pathpubcombo(models.Model):
pathology = models.ForeignKey(Pathology)
publication = models.ForeignKey(Publication)
Run Code Online (Sandbox Code Playgroud)
视图:
def search(request):
pathology_list = Pathology.objects.select_related().order_by('pathology')
Run Code Online (Sandbox Code Playgroud)
视图:
def pathology(request):
pathology_id = request.POST['pathology_id']
p = get_object_or_404(Pathology, pk=pathology_id)
Run Code Online (Sandbox Code Playgroud)
我被困在哪里 我需要python/django语法来编写以下内容:
pathology_id现在必须从表Pathpubcombo(中间manytomany表)中检索publication_id.检索publication_id后,必须使用它来检索发布表中的所有属性,并将这些属性发送到另一个html模板以显示给用户.
你应该使用这里描述的多对多关系:http: //www.djangoproject.com/documentation/models/many_to_many/
喜欢:
class Pathology(models.Model):
pathology = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)
class Publication(models.Model):
pubtitle = models.TextField()
Run Code Online (Sandbox Code Playgroud)
然后
def pathology(request):
pathology_id = request.POST['pathology_id']
p = get_object_or_404(Pathology, pk=pathology_id)
publications = p.publications.all()
return render_to_response('my_template.html',
{'publications':publications},
context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
希望这有效,没有测试过,但你明白了.
编辑:
如果不可能重命名表并使用django的buildin支持,也可以使用select_related().
http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4