django - 如何在 Django 中使用通用 ForeignKey 定义模式
问题描述
我是 Django 新手,我想使用以下逻辑创建模型:
class ExerciseCardio(models.Model):
pass
class ExerciseWeights(models.Model):
pass
class Exercise(models.Model):
name = models.CharField(max_length=100, default='')
EXERCISE_TYPE_CHOICES = (
(1, 'cardio'),
(2, 'Weights'),
)
exercise_type = models.PositiveSmallIntegerField(
choices=EXERCISE_TYPE_CHOICES, default=2)
if exercise_type == 1:
exercise_model_type = models.ForeignKey(ExerciseCardio, on_delete=models.CASCADE, default=0)
elif exercise_type == 2:
exercise_model_type = models.ForeignKey(ExerciseWeights, on_delete=models.CASCADE, default=0)
def __str__(self):
return self.name
我知道它看起来很难看,但必须有办法做到这一点。
解决方案
是的,有一种方法:你可以使用 djangos 的泛型关系。
它的要点如下:
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class Exercise(models.Model):
EXERCISE_TYPE_CHOICES = (
(1, 'cardio'),
(2, 'Weights'),
)
name = models.CharField(
max_length=100, default='')
exercise_type = models.PositiveSmallIntegerField(
choices=EXERCISE_TYPE_CHOICES, default=2)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
在您看来,在创建Exercise
实例时,您必须选择ContentType
正确的模型,可能是这样的:
obj = Exercise()
obj.exercise_type = ...
if obj.exercise_type == 1:
obj.content_type = ContentType.objects.get_for_model(ExerciseCardio)
else:
obj.content_type = ContentType.objects.get_for_model(ExerciseWeights)
推荐阅读
- android - Googole Apps 中的限制政策(不支持的字体系列)
- javascript - 将数组值作为参数传递给函数并创建 json 数据
- python - 删除列表中的单词 - 循环故障
- bash - 我的 AppleScript 运行这么慢是有原因的吗?
- string - 如何用星号替换字符串,除了kotlin中的第一个字符
- django - 如何在 HTML 中关联外键模型
- javascript - 我们如何能够在 javascript 中创建这样的变量?
- python - 理解列表和新文件
- python - 我在构造函数中遇到关键错误,我不知道为什么?
- iis - 获取 HTTP 错误 400 - 标头太长错误