【问题标题】:Django models ForeinKey to abstact classDjango 将 ForeignKey 建模为抽象类
【发布时间】:2016-11-13 21:31:19
【问题描述】:

我正在制作简单的 rpg 浏览器游戏,我想做这个:

#Basic class
class AbstractClass(models.Model):
    health = models.IntegerField(default=10)
    mana = models.IntegerField(default=10)

而且像我这样的职业很少

class WarriorClass(AbstractClass):
    strength = models.IntegerField(default=20)
    intelligence = models.IntegerField(default=10)

class MageClass(AbstractClass):
    strength = models.IntegerField(default=10)
    intelligence = models.IntegerField(default=20)

在 UserProfile 模型中

class UserProfile(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, related_name='profile'
    )
    profession = #??? 

而且我不知道我应该在专业领域做什么。我想要 ForeingKey 之类的东西(但在创建新实例的过程中,我想指定哪个类(法师或战士)应该是这个 ForeignKey。

我该怎么做?或者也许你们有更好的想法来做这样的迷你系统?

最好的

【问题讨论】:

  • 所有职业的属性都一样吗?例如:战士和法师在这方面都只有力量和智慧。

标签: django django-models


【解决方案1】:

您可以使用文档中的 GenericForeignKey

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def __str__(self):
        return self.tag

然后:

>>> from django.contrib.auth.models import User
>>> guido = User.objects.get(username='Guido')
>>> t = TaggedItem(content_object=guido, tag='bdfl')
>>> t.save()
>>> t.content_object
<User: Guido>

但这个解决方案在未来可能会出现问题。 更简单的解决方案呢

  1. 以专业为选择领域
  2. 将你的法力、力量等放入 UserProfile 模型中
  3. 取决于选择设置适当的值

您可以覆盖保存方法,如果用户选择战士将强度设置为 20 等。

【讨论】:

    【解决方案2】:

    在类似情况下检查this answer

    基于此你可以定义:

    class UserProfile(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, related_name='profile'
    )
    profession = models.ForeignKey(WarriorClass)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-15
      • 2015-08-01
      • 2023-04-05
      • 2015-03-19
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多