【问题标题】:Dynamically creating the related_name from META class从 META 类动态创建related_name
【发布时间】:2015-06-01 17:18:48
【问题描述】:

我的大多数 Django 模型都使用相同的 User Mixin,因此我想为该字段动态创建 related_name

我希望它是 TestModel 变为 test_models 的类名,或者甚至是主模型上元类的集合名称。

我查看了self__class__.__name__,但这给了我 User 类的名称。

是否有可能做如下的事情,如果可以的话如何......

class User(models.Model):
    user = models.ForeignKey(USER, related_name=META.related_name)

    class Meta:
        abstract = True


class TestModel(User):
    title = models.CharField(max_length=80)

    class Meta:
        related_name = "test_model"

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    我认为像documented here 那样处理它可能就足够了。

    # myapp/models.py
    class User(models.Model):
        user = models.ForeignKey(
            USER, 
            related_name="%(app_label)s_%(class)s_related"
        )
    
        class Meta:
            abstract = True
    
    
    class TestModel(User):
         title = models.CharField(max_length=80)
    

    这样相关名称将动态变为myapp_testmodel_related。当然,如果确定名称不会在多个应用程序之间发生冲突,您可以调整名称并简化模式。

    【讨论】:

    • app_label 和 class 前面的字符“s”代表什么??
    • @shivam 返回这些变量的小写名称。
    猜你喜欢
    • 2010-09-22
    • 2021-05-02
    • 2018-01-13
    • 2013-09-16
    • 1970-01-01
    • 2012-03-13
    • 2019-10-20
    • 1970-01-01
    相关资源
    最近更新 更多