django - 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
的常规)或服务器日志中没有出现,但字段在查询时返回正确的结果。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>
{% endfor %} <-- This doen't work -->
</td>
<td>
{% for company in object.companies.all %}
<span class="label label-success">{{ company.name }}</span>
{% endfor %} <-- This works :-O -->
</td>
{% endfor %}
起初在我看来,这可能与另一个表或字段存在某种冲突,但我回顾了所有可能性,显然没有任何问题。
解决方案
实际上,这是与另一个应用程序中的另一个表发生冲突。在我拥有的第一个应用程序中:
# 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
推荐阅读
- reactjs - 下一个 JS 图像,我无法使用顺风使图像位置居中
- r - R vlookup 基于最接近的数值变量
- html - 为 aspnet core 中的视图导出或使用 adobe xd 文件
- javascript - Scroll-Snap 滚动时如何阻止用户滚动?
- r - R Shiny / Leaflet 中的时间序列叶绿素
- javascript - 合并两个对象数组并根据对象内部存在的键更新对象
- c# - 旋转四元数
- javascript - 如何根据我的 Java 代码中的条件有条件地在 JavaScript 中调用 alert()?
- gnuplot - 多图叠加图
- prolog - 如何将所有非数字组合到 Prolog 中的列表中?