如何使用装饰器向模型添加字段?

huangapple go评论47阅读模式
英文:

How to add a field to model with a decorator?

问题

我想为我的应用程序中的几乎每个模型都添加外键以允许不同的站点。为此,我认为使用装饰器会很好,因为我只能在某些条件下(例如,如果安装了 Sites)才能添加这些外键。

不幸的是,我的尝试没有做任何事情:

def add_site_fk_field(model_to_annotate: models.Model):
    """Add FK to Site to Model"""
    model_to_annotate.site = models.ForeignKey(Site, on_delete=models.CASCADE)
    return model_to_annotate

@add_site_fk_field
class Test(models.Model):
    ...

是否有可能以某种方式实现这一点?我宁愿不使用抽象类。

英文:

I'd like to add foreign keys to virtually every model in my app to allow different Sites. For this I think it would be nice to use decorators, because I will be able to only add those FKs under certain conditions (e.g. if Sites is installed).

Unfortunately my attempt doesn't do anything:

def add_site_fk_field(model_to_annotate: models.Model):
    """Add FK to Site to Model"""
    model_to_annotate.site = models.ForeignKey(Site, on_delete=models.CASCADE)
    return model_to_annotate

@add_site_fk_field
class Test(models.Model):
    ...

Is it somehow possible to do this? I prefet not to use abstract classes.

答案1

得分: 1

根据我所了解,您无法使用装饰器来完成这个任务。但您可以通过创建一个抽象基本模型类来实现。

例如:

from django.db import models

class Site(models.Model):
    name = models.CharField(max_length=60)

class AddSiteFkField(models.Model):
    fk_site = models.ForeignKey(Site, on_delete=models.CASCADE)

    class Meta:
        abstract = True

class Test(AddSiteFkField):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
英文:

As I know you cant do it with decorator. But you can do that with creating an abstract base model class.

For example:

from django.db import models


class Site(models.Model):
    name = models.CharField(max_length=60)


class AddSiteFkField(models.Model):
    fk_site = models.ForeignKey(Site, on_delete=models.CASCADE)

    class Meta:
        abstract = True


class Test(AddSiteFkField):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

huangapple
  • 本文由 发表于 2023年2月14日 05:23:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定