Hello
Hello

Reputation: 312

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. 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'.

How can I display the organization name here ?

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

<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))

Upvotes: 0

Views: 818

Answers (1)

Dipen Dadhaniya
Dipen Dadhaniya

Reputation: 4630

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. What you need is an object of the Organization model.

Upvotes: 1

Related Questions