【问题标题】:Django : Link Model field to another model field configuration nameDjango:将模型字段链接到另一个模型字段配置名称
【发布时间】:2018-01-25 14:56:31
【问题描述】:

在 Django 中给出以下模型:

class MyModel(models.Model):
    name = models.CharField('This is my name'),max_length=150)

class AnotherModel(models.Model):
    my_model_field_name = [...]

我想在AnotherModel.my_model_field_name 中存储MyModel.name 字段的名称(所以“这是我的名字”)。 我希望它被链接,所以如果明天我将MyModel.name 字段的名称更改为“这是我的新名称”,我希望我以前的所有AnotherModel.my_model_field_name 记录自动更新。

模型实例能够链接到其他模型实例,而不是模型本身,对吧?

这可能还是只是愚蠢?

编辑:

我找到了一个解决方案:Django ContentType 表非常适合这样做。

使用内容类型,您可以遍历模型的字段,而无需模型实例(我的意思是,我的 MyModel 表中的一行),因此,例如,我可以执行类似的操作:

from django.contrib.contenttypes.models import ContentType
from .models import MyModel

# get the model I want
my_model = ContentType.objects.get_for_model(MyModel)

# get all fields of this model
fields = model._meta.get_fields()

# Iterate over the fields to find the one I want, and read it's specifications
for field in fields:
    # all my stuff here

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    我认为正确的做法是:

    class MyModel(models.Model):
        name = models.CharField('This is my name'),max_length=150)
    
    class AnotherModel(models.Model):
        my_model = models.ForeignKey(MyModel)
    

    因此,如果您需要从 AnotherModel 中读取 MyModel 名称字段,您可以这样做:

    another_model = AnotherModel.objects.last()
    another_model.my_model.name
    

    通过这种方式,AnotherModel 有一个指向 MyModel 的链接,当您更改 MyModel 名称字段时,它将反映在 AnotherModel 对象中。

    【讨论】:

    • 感谢您抽出宝贵时间 Mau,实际上,您的解决方案的问题是我的数据库中始终需要有一个 MyModel 对象才能工作。我找到了另一个解决方案:(见我的编辑)
    猜你喜欢
    • 2017-01-31
    • 1970-01-01
    • 2019-03-11
    • 2015-09-26
    • 2021-10-05
    • 2021-09-16
    • 2017-11-21
    • 2010-10-18
    • 1970-01-01
    相关资源
    最近更新 更多