简体   繁体   中英

How i could use the “username” from the User model as id in other model in Django?

I'm new in this and I'm trying to use in Django the username as id in other model. I imported the base model for User in Django, but when i'm doing:

 author = User().get_username()

The field doesn't appear.

Is there any method to use the "username" from the User model?

Thanks for your help and sorry for my English.

You need to use ForeignKey to relate your current model with User model to access its methods.

class MyModel(models.Model):
    author = models.ForeignKey('User', on_delete=models.CASCADE)
    ...

Then you can call .get_username() method to retrieve username. Assuming my_obj is MyModel class object, calling my_obj.author.get_username() will do the job.

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