gpt4 book ai didi

Django 模型中的多态性

转载 作者:行者123 更新时间:2023-12-02 02:35:03 24 4
gpt4 key购买 nike

我想为不同的玩家设置不同的运动项目 像下面这样。有办法做到这一点吗?

示例模型:

class Player(models.Model):
id = models.AutoField(primary_key=True)
sportType = models.CharField(max_length=15)
sportObj = generic.GenericForeignKey('content_type')

class Icehockey(models.Model):
id = models.AutoField(primary_key=True)
stick_brand = models.CharField(max_length=50)
skate_number = models.IntegerField()

class Basketball(models.Model):
id = models.AutoField(primary_key=True)
ball_brand = models.CharField(max_length=50)
uniform_color= models.CharField(max_length=10)

class Football(models.Model):
id = models.AutoField(primary_key=True)
shoeNumber = models.IntegerField()
uniform_size = models.CharField(max_length=10)

用法示例:

player1 = Player.objects.get(id=1).sportObj // returns <Icehockey object>
player2 = Player.objects.get(id=2).sportObj // returns <Basketball object>
player3 = Player.objects.get(id=3).sportObj // returns <Football object>
player4 = Player.objects.get(id=4).sportObj // returns <Football object>

编辑:Django 网站上有一个关于 How content types works 的文档如果有人需要的话。

最佳答案

您提供的示例对我来说看起来不错,我对模型进行了一些修改以使其可用。

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class Player(models.Model):
SPORT_CHOICES = (
('I', 'Icehockey'),
('B', 'Basketball'),
('F', 'Football'),
)
sportType = models.CharField(max_length=15,choices=SPORT_CHOICES)
sportObj = GenericForeignKey('content_type', 'object_id')
object_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)

class Icehockey(models.Model):
stick_brand = models.CharField(max_length=50)
skate_number = models.IntegerField()

class Basketball(models.Model):
ball_brand = models.CharField(max_length=50)
uniform_color= models.CharField(max_length=10)

class Football(models.Model):
shoeNumber = models.IntegerField()
uniform_size = models.CharField(max_length=10)

关于Django 模型中的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36026693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com