简体   繁体   中英

Set the value of a field in a model as the value of a field in another model in django

I have a two model field one which is the user model and one which is the landlord model. I want the first_name and last_name of the user model to be saved also in the landlord model.

This is my model view

  pass

class User(AbstractUser):
    is_customer = models.BooleanField(default=False)
    is_employee = models.BooleanField(default=False)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    nin = models.IntegerField(unique = True , null=True)
    avatar = models.ImageField(null= True, default="avatar.svg")

    objects = UserManager()

class Landlord(models.Model):
    user = models.OneToOneField(User, null= True, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=200, null=True)
    last_name = models.CharField(max_length=200, null=True)
    email = models.EmailField(unique = True , null=True)
    bio = models.TextField(null=True)
    nin = models.IntegerField(unique = True , null=True)
    avatar = models.ImageField(null= True, default="avatar.svg")
    
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS= []
   
    objects = User()

    def __str__(self):
        return str(self.user)```
    
    

Instead of creating such model decide to do one of solutions:

  1. Inherit from User model:

     class Landlord(User):
  2. Make User universal model with a flag if it is a Landlord user:

     class User(AbstractUser): ... is_landlord = models.BooleanField(default=False)

With option 2 just everywhere you need only Landlord things use if user.is_landlord: or in templates: {% if user.is_landlord %} etc.

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