我想用相关的数据库列为Django对象添加一个字段。如果在初始化模型后设置属性,只需添加一个属性就行了,但是像往常一样,我试图让它以Django的方式工作。
class Stuff(models.Model):
id = fields.UUIDField(primary_key=True)
name = models.CharField(max_length=128)
enabled = models.BooleanField(default=False)
log_user = None
这没有任何问题。
stuff = Stuff()
stuff.log_user = current_user
这不是
stuff = Stuff(log_user=current_user)
TypeError: 'log_user' is an invalid keyword argument for this function
有没有办法让字段表现为Django方式?
答案 0 :(得分:1)
您需要ForeignKey。
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 :(得分:1)
如果您执行以下操作,构造函数将起作用:
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
答案 2 :(得分: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()