user8563636
user8563636

Reputation: 143

Why can't I put value to db?

I made composite id of trunsaction_id&user_id.I wanted to assign trunsaction_id each user_id.Now User model is

class User(models.Model):
    trunsaction_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    regist_date = models.DateTimeField(auto_now=True)
    user_id = models.CharField(max_length=200,null=True)
    name = models.CharField(max_length=200,null=True)
    age = models.CharField(max_length=200,null=True)
    user_trunsaction_id = ''.join([str(trunsaction_id), '_', str(user_id)]

But when I run file of putting data to User model, all column excepting for user_trunsaction_id has its data, but no user_trunsaction_id's column is db.Of course I run makemigration&migration command,so I really cannot understand why this error happens.What is wrong?How can I fix this?

Upvotes: 0

Views: 30

Answers (2)

Nils Werner
Nils Werner

Reputation: 36839

You need to define your computed property like

class User(models.Model):
    trunsaction_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    regist_date = models.DateTimeField(auto_now=True)
    user_id = models.CharField(max_length=200,null=True)
    name = models.CharField(max_length=200,null=True)
    age = models.CharField(max_length=200,null=True)

    @property
    def user_trunsaction_id(self):
        return '%s_%s' % (self.trunsaction_id, self.user_id)

Upvotes: 0

Beomi
Beomi

Reputation: 1727

First of all, Django reads your class in models.py to make db scheme.

But at your code user_trunsaction_id is NOT db field but just User class's attribute.

So if you want to use user_trunsaction_id like db field, do like this:

class User(models.Model):
    trunsaction_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    regist_date = models.DateTimeField(auto_now=True)
    user_id = models.CharField(max_length=200,null=True)
    name = models.CharField(max_length=200,null=True)
    age = models.CharField(max_length=200,null=True)

    @property
    def user_trunsaction_id(self):
        return ''.join([str(self.trunsaction_id), '_', str(self.user_id)]

then you can get user_trunsaction_id like this:

User.objects.get(pk=1).user_trunsaction_id

Upvotes: 1

Related Questions