我正在尝试创建自定义的ForeignKey。我继承了它并试图覆盖__init__
方法以提供位置参数to
和on_delete
,如下所示:
from django.contrib.auth.models import User
class CurrentUserField(models.ForeignKey):
def __init__(self, **kwargs):
super().__init__(User, models.CASCADE, **kwargs)
class DemoModel(models.Model):
owner = CurrentUserField()
info = models.TextField()
当我运行makemigrations
时,它会给我以下错误:
TypeError: __init__() got multiple values for argument 'on_delete'
我似乎无法弄清问题是什么。我只为两个位置参数提供两个值。
答案 0 :(得分:2)
假设您在所有者字段中传递User
和on delete
参数,您可以看到Django如何转换其参数。
实施例
from django.db import models
from django.contrib.auth.models import User
class CurrentUserField(models.ForeignKey):
def __init__(self, *args, **kwargs):
for i in args:
print(i, "This is an argument")
for j in kwargs.items():
print(j, "This is a keyword argument")
super().__init__(*args, **kwargs)
class DemoModel(models.Model):
owner = CurrentUserField(User, on_delete=models.CASCADE)
info = models.TextField()
输出
<class 'django.contrib.auth.models.User'> This is an argument
('on_delete', <function CASCADE at 0x103900400>) This is a keyword argument
('on_delete', <function CASCADE at 0x103900400>) This is a keyword argument
('to', 'auth.User') This is a keyword argument
('on_delete', <function CASCADE at 0x103900400>) This is a keyword argument
('to', 'auth.User') This is a keyword argument
正如您所看到的,Django正在将auth.User
和models.CASCADE
转换为分别包含密钥to
和on_delete
的字典。即,{'to': 'auth.User', 'on_delete': <function CASCADE at 0x103900400>}
。
因此,在您的情况下,您应该为键to
和on_delete
设置默认值以获得预期的行为。
即,
from django.db import models
from django.contrib.auth.models import User
class CurrentUserField(models.ForeignKey):
def __init__(self, *args, **kwargs):
kwargs.setdefault('to', User)
kwargs.setdefault('on_delete', models.CASCADE)
super().__init__(*args, **kwargs)
class DemoModel(models.Model):
owner = CurrentUserField()
info = models.TextField()