Home > Mobile >  Django model field values returning blank?
Django model field values returning blank?

Time:12-31

I'm a Django Beginner. I have a model named "Person" with two character fields - first_name and last_name. I have migrated them using makemigrations in the shell and have set the value of first_name to my first name. However, whenever I try to set a value for last_name it returns blank. For example:

 a = Person(last_name="...")
 a.save()
 a.id
 id=...
 Person.objects.get(id=...)
 <Person: >

The value will just be blank in the brackets. Here is my models.py if it's relevant:

 from django.db import models

 class Person(models.Model):
      first_name = models.CharField(max_length=15)
      last_name = models.CharField(max_length=6)

      def __str__(self):
         return self.first_name

I'm not entering a value that is beyond the max_length. Thanks for your time.

CodePudding user response:

The __str__ only returns the self.first_name hence it means that it will print the Person as <Person: last_name> with last_name the last_name of the Person.

If you thus rewrite this to:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=15)
    last_name = models.CharField(max_length=6)

    def __str__(self):
        return f'{self.first_name} {self.last_name}'

it will print the person object with its first and last name.

But saving it in the database, and retrieving it works, regardless of the implementation of __str__.

If you for example obtain the .last_name attribute, it will print:

>>> Person.objects.get(id=some_id).last_name
'...'
  • Related