如何遍历django模板中的相关对象列表?

时间:2016-06-21 22:00:55

标签: python django many-to-many

我是Django的新手,我正在尝试在视图中打印相关模型。我很确定数据库本身设置正确,包括密钥等,表格中有数据可供使用。我不确定的是

  • 我是否将模型连接到正确的表格和列名称?
  • 我为每位选民加载手机吗?
  • 如何迭代关系本身?

我可以自己获取选民信息,但我尝试使用相关的$("#search").on("keyup", function() { var value = $(this).val(); $("table tr").hide(); $("table tr").each(function(index) { if (index !== 0) { $row = $(this); //$(this).hide(); var id = $row.find(".assertionResult").text(); if (id.indexOf(value) === 0) { var x = $(".testTitle"); var y = $(".testResult"); $(this).show(); x.parent().show(); y.parent().show(); } } }); }); 模型无效。

表:

Phone

型号:

voters:
  id int primary key
  first_name varchar

phones:
  id int primary_key
  phone_number varchar

voter_phones:
  voter_id FK
  phone_id FK

观点:

from django.db import models


class Phone(models.Model):
    phone_number = models.CharField(max_length=255)

    class Meta:
        db_table = 'phones'


class Voter(models.Model):
    first_name = models.CharField(max_length=255)
    phones = models.ManyToManyField('Phone', through='VoterPhone', related_name='voters', through_fields=('voter_id', 'phone_id'))

    class Meta:
        db_table = 'voters'


class VoterPhone(models.Model):
    voter = models.ForeignKey('Voter', related_name='voter_phones')
    phone = models.ForeignKey('Phone', related_name='voter_phones')

    class Meta:
        db_table = 'voter_phones'

模板:

def results(request):
    voters = Voter.objects.all()
    return render(request, 'site/results.html', {'voters': voters})

最终结果是选民姓名列表,没有电话号码。我错过了什么?

编辑:我创建了一个本地数据库,生成并运行了django迁移,并插入了一些虚拟数据。我仍然没有电话号码。

2 个答案:

答案 0 :(得分:0)

如果不使用Django创建数据库,则需要为VoterPhone类指定表名。 Django不会选择选举电话表作为中间表。我认为通过设置 类Meta:         db_table ='voterphones' 对于VoterPhone课程,您应该能够看到相关的电话号码。

答案 1 :(得分:0)

我终于有了一些工作。我不得不做出以下改变:

  • 将表重命名为默认的django名称(即elections_phones而不是voter_phones)

  • 发现vot_phones中的外键是int(11),而选民和手机中的主键都是bigint(20)

  • 删除了联接模型

感谢您的帮助,伙计们。