首页 > 解决方案 > ManyToManyField 在 shell 上工作但不在服务器上

问题描述

这是我见过的更罕见的行为。我在一张桌子上有两个 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的常规)或服务器日志中没有出现,但字段在查询时返回正确的结果。ReportListgeneric.ListViewcompanies

# 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 %}

起初在我看来,这可能与另一个表或字段存在某种冲突,但我回顾了所有可能性,显然没有任何问题。

标签: djangomanytomanyfield

解决方案


实际上,这是与另一个应用程序中的另一个表发生冲突。在我拥有的第一个应用程序中:

# 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)
    ...

我只需要related_name在 app2 外键中添加一个特定的。总是建议添加这个独特的related_name以避免这种问题:-S


推荐阅读