1

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?

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Working perfectly. Thanks. Just wish there was a meta_field in Django, so we don't have to jump through hoops to do something this simple.
1

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)

1 Comment

Unfortunately this will still create a db column.
0
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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.