在这里,我正在过滤与django User模型具有OnetoOne关系的人员。下面的功能def filter_staff_users(request):
的代码也可以按我的要求很好地工作,但是我得到的问题是在消息中显示组织名称时。我尝试做organization.name
,但没有成功。我得到了'str' object has no attribute 'name'
,当我尝试转换int organization = int(request.GET.get('organization'))
时,它再次抛出了'int' object has no attribute 'name'
。
如何在此处显示组织名称?
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')
在添加staff_user时,我按如下所示添加了组织
<select name="organization">
{% for organization in organizations %}
<option value="{{organization.pk}}" >{{organization.name}}</option>
{% endfor %}
</select>
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))
答案 0 :(得分:1)
尝试做:
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)
这样做:
organization = request.GET.get('organization')
我们只得到pk (as a string)
中的organization
。您需要的是Organization
模型的对象。