Home > Back-end >  Django models equal one filed to another
Django models equal one filed to another

Time:02-23

i try to equal owner_id to id , i mean when user's id is 1 and create organization i want to owner_id also be 1 . what is best way?

class Organization(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(default='0000000',max_length=100)
    type = models.CharField(default='0000000',max_length=20)
    owner_id = models.CharField(id,max_length=100)

    def __str__(self):
        return str(self.name)

this not working owner_id = models.CharField(id,max_length=100)

CodePudding user response:

What you actually need is OneToOne relation.

class Organization(models.Model):
    id = models.AutoField(primary_key=True)
    ...
    owner = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)

With that, assuming that organization is an Organization object, you can call Owner object or id this way:

 organization.owner      # get Owner (User) object
 organization.owner.id   # get id of Owner (User)

CodePudding user response:

If you just want to read owner_id, you can add a property in your model like that:

class Organization(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(default='0000000',max_length=100)
    type = models.CharField(default='0000000',max_length=20)

    def __str__(self):
        return str(self.name)

    @property
    def owner_id(self):
        return self.id

This will ensure that, owner_id is always same value as id, but you cannot change it later, it's just a representation of id with another name

  • Related