gpt4 book ai didi

python - 在 Django 模板中显示外键值

转载 作者:太空狗 更新时间:2023-10-30 02:06:23 25 4
gpt4 key购买 nike

这是我的问题。我是 python/django 的新手(大约 2 个月)。我有 2 个表,项目和状态。我有一个从状态指向项目的外键,我希望尝试在我的项目模板上显示外键(状态)的值,而不是外键的地址。

这是我的模型.py

from django.db import models
from clients.models import Clients
from django.contrib.auth.models import User
from settings import STATUS_CHOICES

from django.db import models
from clients.models import Clients
from django.contrib.auth.models import User
from settings import STATUS_CHOICES

class Project(models.Model):
client = models.ForeignKey(Clients, related_name='projects')
created_by = models.ForeignKey(User, related_name='created_by')


#general information
proj_name = models.CharField(max_length=255, verbose_name='Project Name')
pre_quote = models.CharField(max_length=3,default='10-')
quote = models.IntegerField(max_length=10, verbose_name='Quote #', unique=True)
desc = models.TextField(verbose_name='Description')
starts_on = models.DateField(verbose_name='Start Date')
completed_on = models.DateField(verbose_name='Finished On')

def __unicode__(self):
return u'%s' % (self.proj_name)


class Status(models.Model):
project = models.ForeignKey(Project, related_name='status')
value = models.CharField(max_length=20, choices=STATUS_CHOICES, verbose_name='Status')
date_created= models.DateTimeField(auto_now=True)

def __unicode__(self):
return self.value

class Meta:
verbose_name = ('Status')
verbose_name_plural = ("Status")

我的观点.py

@login_required
def addProject(request):
if request.method == 'POST':
form = AddSingleProjectForm(request.POST)
if form.is_valid():
project = form.save(commit=False)
project.created_by = request.user
project.save()
project.status.create(
value = form.cleaned_data.get('status', None)
)
return HttpResponseRedirect('/project/')
else:
form = AddSingleProjectForm()

return render_to_response('project/addProject.html', {
'form': form, 'user':request.user}, context_instance=RequestContext(request))

最后是我的模板:

{% if project_list %}
<table id="plist">
<tr id="plist">
<th>Quote #</th>
<th>Customer</th>
<th>Date</th>
<th>Project Name</th>
<th>Status</th>
<th>Contact</th>
</tr id="plist">
{% for p in project_list %}
<tr id="plist">
<td><a href="/project/{{ p.id }}/view">{{ p.pre_quote }}{{ p.quote }}</a></td>
<td>{{ p.client }}</td>
<td>{{ p.starts_on }}</td>
<td>{{ p.proj_name }}</td>
<td>{{ p.status_set.select_related }}</td>
<td>{{ p.created_by }}</td>
</tr>
{% endfor %}
</table>

{% else %}
<p>No projects available.</p>
{% endif %}

任何帮助将不胜感激。谢谢!

最佳答案

我猜你的意思是:

<td>{{ p.status_set.select_related }}</td>

这没有做任何事情。 select_related 是一个优化功能,与实际获取或显示相关内容无关。如果你想这样做,你将不得不遍历 p.status_set.all 的结果。

关于python - 在 Django 模板中显示外键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3969640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com