当用户创建模型House的实例时,我正在尝试创建Car实例。
Models.py
class House(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
address = models.CharField(max_length=100)
def __str__(self):
return self.user.username
class Car(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
makemodel = models.CharField(max_length=100)
def __str__(self):
return self.user.username
def create_car(sender, **kwargs):
if kwargs['created']:
car = Car.objects.create(user=kwargs['instance'])
post_save.connect(create_car, sender=House) #have to figure out how to have multiple senders
当我进入管理员并为任何用户创建House模型的实例时,我收到以下错误。
"Cannot assign "<House: jason>": "Car.user" must be a "User" instance."
任何想法都将不胜感激!
答案 0 :(得分:2)
您需要传递user
参数用户实例,但在create_car
,因为发件人是House
,实例参数的类型为House
。
您可以这样做:
def create_car(sender, **kwargs):
if kwargs['created']:
car = Car.objects.create(user=kwargs['instance'].user)