【发布时间】: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