简体   繁体   中英

Django model field values returning blank?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM