2

In Chinese, the name format is 'LastnameFirstname' (number of characters for both Lastname and Firstname are varied), while in English, it is 'Firstname LastName'. We can see that in Chinese, the first name last name is swapped (which is not a problem in query here), and the first name last name is NOT separated by whitespace (which caused me this problem).

In SQL, we can do this:

SELECT * 
FROM   USER 
WHERE  Concat(last_name, first_name) = 'LastnameFirstName'; 

But how can I do this in Django? Given a FULLNAME string as 'LastnameFirstname', how can I do:

User.objects.filter(last_name+firstname=FULLNAME)

Another solution is to create a custom User model and create a new field called "full name", but this solution disables me to use other django built-in functions:

class User( models.Model ):
    first_name = models.CharField( max_length=64 )
    last_name = models.CharField( max_length=64 )
    full_name = models.CharField( max_length=128 )
    def save( self, *args, **kw ):
        self.full_name = '{0}{1}'.format( first_name, last_name )
        super( User, self ).save( *args, **kw )

I guess there would be a better solution.

Thanks. :)

Community
  • 1
  • 1
Daniel
  • 981
  • 3
  • 11
  • 15

1 Answers1

0

You can either link to the User model and create your own class:

class UserProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)

    def full_name(self):
        return self.user.last_name + self.user.first_name
    ....

or you could subclass the AbstractUser model to define your own custom user attributes there:

from django.contrib.auth.models import AbstractUser

class MyUser(AbstractUser):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

    def full_name(self):
        return self.last_name + self.first_name

Then in your settings set the default user model to your new class:

AUTH_USER_MODEL = 'myapp.MyUser'

The AbstractUser model only has 3 attributes: password,last_login and is_active. You can define the rest yourself.

phalt
  • 1,244
  • 1
  • 10
  • 21