Khubaib Khawar
Khubaib Khawar

Reputation: 71

How do I define __str__() method in a model which has a Foreign Key of User model and get the values of fields in Django?

I have below model in my Django app and it has a Foreign Key of Django's default User Model with a __str__() method.

class Subject(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, max_length=100)
    subject = models.CharField(max_length=100)

    def __str__(self):
        return f'{self.user.username}'

I want to show the subject name in the Admin Panel, when we open the Subjects Model/Table in the Admin Panel. Suppose that if we have a user with username 'khubi' and he has two subjects, then the Admin Panel just shows the username of the user that is 'khubi' instead of showing the subject's names. Below is the screenshot:

subject.png

I have tried to put this:

return f'{self.user.username.subject}'

But it gives the error that 'str' object has no attribute 'subject'

and I have tried it as well:

return f'{self.user.subject}'

and it gives me the error 'User' object has no attribute 'subject'

How can I get the name of the subject in the __str__() method and anywhere outside as well?

Upvotes: 1

Views: 323

Answers (2)

Jorge Luis
Jorge Luis

Reputation: 955

return f'{self.subject}'

is your correct way of access to the field subject, because self.user.subject is not part of the users fields. Maybe you should add a related_name to your field definition in the user, like this:

class Subject(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE,
                                max_length=100, related_name='subjects')
    # ...

In that way you can access from the users to their submitted subjects just asking the user object for its subjects: subjects = user.subjects as the others field.

Upvotes: 0

Hisham___Pak
Hisham___Pak

Reputation: 1490

You'll need to call self.subject for subject.

class Subject(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, max_length=100)
    subject = models.CharField(max_length=100)

    def __str__(self):
        return '{} ({})'.format(self.subject, self.user.username)

The given code will return some_subject (khubi)

Upvotes: 2

Related Questions