[英]Django. Why would my foreign key does not match the same data from parent primary key
我有 2 個模型:
class Director(models.Model):
director_name = models.TextField(primary_key=True)
director_firstname = models.CharField(max_length=32)
def __str__(self):
return f'{self.director_name}'
def get_absolute_url(self):
return reverse('director-detail', args=[str(self.director_name)])
class Meta:
managed = False
db_table = 'director'
ordering = ['director_name']
class Connection(models.Model):
director_connect = models.ForeignKey('Director', models.DO_NOTHING, db_column='director_connect')
worker_connect = models.ForeignKey('Worker', models.DO_NOTHING, db_column='worker_connect')
class Meta:
managed = False
db_table = 'connection'
unique_together = (('director_connect', 'worker_connect'),)
ordering = ['director_connect']
def __str__(self):
return f'{self.director_connect}'
def get_absolute_url(self):
return reverse('director-detail', args=[str(self.director_connect)])
這是我的 view.py 文件:
class DirectorDetailView(generic.DetailView):
model=Director
template_name = 'company/director_detail.html'
def get_context_data(self, **qwargs):
a = super(DirectorDetailView, self).get_context_data(**qwargs)
a['cons'] = Connection.objects.all()
return a
當我嘗試將 html 中的 2 列與 for 循環和 if 語句相匹配時,它們不匹配,盡管它們是一對一的副本:
{% extends "index.html" %}
{% block content %}
<h1>{{ director.director_name }}</h1>
<p>{{ director.firstname }}</p>
{% for con in cons %}
{% if object.director_name == con.director_connect %}
<li>{{con.id}}, {{con.director_connect}}, {{con.worker_connect}}</li>
{% endif %}
{% endfor %}
{% endblock %}
我該如何解決? 我想把工人名單帶到主任名下。 任何指向可能答案的鏈接(我正在尋找它,但我找不到它)或朝着正確的方向輕輕推動都會很好。
問題在於,在您的模板中,您將主管的姓名與Connection
中通過 director_connect ForeignKey
引用的主鍵進行比較。 最簡單的解決方案是更改 if 表達式:
{% extends "index.html" %}
{% block content %}
<h1>{{ director.director_name }}</h1>
<p>{{ director.firstname }}</p>
{% for con in cons %}
{% if object == con.director_connect %} // Change it so it compares the primary key
<li>{{con.id}}, {{con.director_connect}}, {{con.worker_connect}}</li>
{% endif %}
{% endfor %}
{% endblock %}
實現此目的的其他方法是使用過濾器在視圖中按主管過濾工人:
class DirectorDetailView(generic.DetailView):
model=Director
template_name = 'company/director_detail.html'
def get_context_data(self, **qwargs):
a = super(DirectorDetailView, self).get_context_data(**qwargs)
director = self.get_object()
a['cons'] = Connection.objets.filter(direct_connect=director).all()
return a
這更好,因為它將使用 SQL 過濾數據庫中的工作人員,這可能比模板引擎更快。
其他解決方案是使用ManyToManyField並讓 django ORM 為您處理關系,但這需要重構代碼並且可能需要一些數據庫遷移。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.