ManyToManyField在shell上工作但不在服务器上工作

时间:2018-05-03 11:22:33

标签: django manytomanyfield

这是我见过的罕见的行为。我在桌子上有两个ManyToMany关系:

# models.py

...

class Customer(models.Model):
    name = models.CharField('Name', max_length=128)
    ...

class Report(models.Model):
    ...
    companies = models.ManyToManyField(Company)
    customers = models.ManyToManyField(Customer)
    ...

表单是普通表单,没有自定义save()

当我通过webapp创建一个Report对象时,我可以在shell上成功查询它们:

In [3]: report.customers.all()
Out[3]: <QuerySet [<Customer: xxxxxxx>]>

但是在服务器上(我使用gunicorn),浏览器上没有出现customers(通过基于ReportList的常规generic.ListView),或者在我查询时出现在服务器日志中,但是companies字段会在查询中返回正确的结果。

# views.py
from core import models

class ReportList(LoginRequiredMixin, PermissionRequiredMixin, generic.ListView):
    permission_required = 'core.add_report'
    model = models.Report

这里是模板......

# report_list.html

{% for object in object_list %}
<td>
    {% for customer in object.customers.all %}
    <span class="label label-success">{{ customer.name }}</span>&nbsp;
    {% endfor %} <-- This doen't work -->
</td>
<td>
    {% for company in object.companies.all %}
    <span class="label label-success">{{ company.name }}</span>&nbsp;
    {% endfor %} <-- This works  :-O -->
</td>
{% endfor %}

起初我认为它可能与另一个桌子或领域发生某种冲突,但我会审查所有可能性,并且没有任何明显的错误。

1 个答案:

答案 0 :(得分:0)

确实,这与另一个应用程序中的另一个表发生冲突。在我的第一个应用程序中:

# app1 models.py
...

class Customer(models.Model):
    name = models.CharField('Name', max_length=128)
    ...

class Report(models.Model):
    ...
    companies = models.ManyToManyField(Company)
    customers = models.ManyToManyField(Customer)
    ...

在其他应用中,我有:

# app2 models.py
...

from app1.models import Customer

class Report(models.Model):
    ...
    customer = models.ForeignKey(Customer)
    ...

我只需要在app2外键中添加特定的related_name。始终建议添加此唯一related_name以避免此类问题:-S