[英]How to display foreign key value instead of pk in django?
Here I am filtering staffs which has OnetoOne relation with the django User model.And the below code of function def filter_staff_users(request):
also works fine as I wanted but the problem what I get is while displaying the organization name in message.I tried doing organization.name
but it didn't worked. 在这里,我正在过滤与django User模型具有OnetoOne关系的人员。以下函数def filter_staff_users(request):
代码也可以按我的要求很好地工作,但是我得到的问题是在消息中显示组织名称时我尝试了做organization.name
但没有成功。 I got 'str' object has no attribute 'name'
and when I tried converting int organization = int(request.GET.get('organization'))
then it again throws 'int' object has no attribute 'name'
. 我得到了'str' object has no attribute 'name'
,当我尝试转换int organization = int(request.GET.get('organization'))
它再次抛出了'int' object has no attribute 'name'
。
How can I display the organization name here ? 如何在此处显示组织名称?
models.py models.py
class Organization(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
class Staff(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff')
name = models.CharField(max_length=255, blank=True, null=True)
organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True, related_name='staff')
While adding the staff_user i added the organization as below 在添加staff_user时,我添加了以下组织
<select name="organization">
{% for organization in organizations %}
<option value="{{organization.pk}}" >{{organization.name}}</option>
{% endfor %}
</select>
views.py views.py
def filter_staff_users(request):
year = request.GET.get('year')
month = request.GET.get('month')
# month_name = calendar.month_name[int(month)]
organization = request.GET.get('organization')
print('org', type(organization))
if year and month and organization:
staffs = get_user_model().objects.filter(Q(staff__joined_date__year=year) & Q(staff__joined_date__month=month) & Q(staff__organization=organization))
messages.success(request, '{} staffs found for {} {} and {}'.format(staffs.count(), year, calendar.month_name[int(month)], organization))
Try doing: 尝试做:
from django.shortcuts get_object_or_404
def filter_staff_users(request):
# ...
organization = get_object_or_404(Organization, pk=request.GET.get('organization'))
print(organization.name)
By doing: 通过做:
organization = request.GET.get('organization')
We only get the pk (as a string)
of the organization
. 我们只得到了pk (as a string)
的的organization
。 What you need is an object of the Organization
model. 您需要的是Organization
模型的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.