Dax
Dax

Reputation: 369

Django model field with database column

I would like to add a field to a Django object with the related database column. Just adding an attribute will work if a set the attribute after initializing the model, but as usual, I'm trying to get it to work the Django way.

class Stuff(models.Model):
    id = fields.UUIDField(primary_key=True)
    name = models.CharField(max_length=128)
    enabled = models.BooleanField(default=False)
    log_user = None

This will work without any problems.

stuff = Stuff()
stuff.log_user = current_user

This doesn't

stuff = Stuff(log_user=current_user)
TypeError: 'log_user' is an invalid keyword argument for this function

Is there any way to have the field behave the Django way?

Upvotes: 1

Views: 717

Answers (3)

Invincible
Invincible

Reputation: 422

Django recommend to use as a Foreign key Concept:

class Stuff(models.Model):
    id = fields.UUIDField(primary_key=True)
    name = models.CharField(max_length=128)
    enabled = models.BooleanField(default=False)
    log_user = models.ForeignKey('auth.User', blank=True, null=True)

while saving your Data you can add log_user object:
     Stuff = Stuff()
     stuff.log_user = user
     stuff.save()

Upvotes: 0

Mariusz Jamro
Mariusz Jamro

Reputation: 31643

The constructor will work if you do:

class Stuff(models.Model):

    id = fields.UUIDField(primary_key=True)
    name = models.CharField(max_length=128)
    enabled = models.BooleanField(default=False)
    log_user = None

    def __init__(self, log_user=None, *args, **kwargs):
        super(Stuff, self).__init__(*args, **kwargs)
        self.log_user = log_user

Upvotes: 1

DrTyrsa
DrTyrsa

Reputation: 31951

You need ForeignKey here.

class Stuff(models.Model):
    id = fields.UUIDField(primary_key=True)
    name = models.CharField(max_length=128)
    enabled = models.BooleanField(default=False)
    log_user = models.ForeignKey('auth.User', blank=True, null=True)

Upvotes: 1

Related Questions