如何从ForeignKey继承扩展模型字段?

2024-09-26 17:55:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建自定义外键。我继承了它,并尝试重写__init__方法来提供位置参数to和{},如下所示:

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时,会出现以下错误:

^{pr2}$

我好像搞不清问题出在哪里。我只为两个位置参数提供两个值。在


Tags: todjango方法fromimportauth参数init
1条回答
网友
1楼 · 发布于 2024-09-26 17:55:51

假设您在owner字段中传递Useron 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()

输出

^{pr2}$

如您所见,Django正在将auth.User和{}分别转换为一个具有to和{}键的字典。i、 例如,{'to': 'auth.User', 'on_delete': <function CASCADE at 0x103900400>}。在

所以在您的例子中,您应该为键toon_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()

相关问题 更多 >

    热门问题