在Django中从另一个模型的实例创建模型实例,而不链接到原始实例源

时间:2011-12-11 18:49:18

标签: python django database-design django-models

我正在制作游戏。玩家的库存持有武器。武器是武器模型的实例。创建新武器时,从模板模型实例中随机选择武器模板。比复制所有字段以创建武器实例。为此,我使用此功能:

class ItemModel(models.Model):
    def fromTemplate(self, templateInstance):
       if issubclass(type(self), type(templateInstance)):
          for field in templateInstance._meta.fields:
                setattr(self, str(field.name), getattr(templateInstance, field.name))
          self.pk = None
          self.save()
          for m2mField in templateInstance._meta.many_to_many:
            setattr(self, m2mField.name, getattr(templateInstance, m2mField.name).all())

    class Meta:
    abstract = True

以下是模型定义:

class WeaponTemplate(ItemModel):
   def __unicode__(self):
      return str(self.id)
   type = models.CharField(max_length=100, choices = TYPE_CHOICES)
   category = models.CharField(max_length=100, choices = CATEGORY_CHOICES)
   group = models.CharField(max_length=100, choices = GROUP_CHOICES)
   name = models.CharField(max_length=25)
   level = models.IntegerField(default=1)
   frequency = models.IntegerField(default = 100)
   rarity = models.CharField(max_length=8, choices = RARITY_CHOICES)
   multiplier = models.IntegerField()
   buyCost = models.IntegerField()
   sellValue = models.IntegerField(blank=True, null=True)

class Weapon(WeaponTemplate):
   def __unicode__(self):
      return self.name 

现在我的问题是“fromTemplate”函数还在模板模型中添加了一个新实例。所以当我这样做时:

randomWeaponTemplate = random.choice(WeaponTemplate.objects.all())
newWeapon = Weapon()
newWeapon.fromTemplate(randomWeaponTemplate)
newWEapon.save()

我在WeaonTemplate表中看到了一个新条目。我应该如何修改我的代码以使两个模型独立存储,以便在从weaponTemplate创建新武器时,不会对WeaponTemplate表进行任何添加?

1 个答案:

答案 0 :(得分:0)

我认为你不应该在武器和武器模板之间使用继承,django将继承视为OneToOneRelationship。如果你想让你的代码更干,你可以尝试这样做:

from django.db import models
from django.db.models.manager import Manager


class WeaponBase(models.Model):
    def __unicode__(self):
        return str(self.id)

    name = models.CharField(max_length=25)
    level = models.IntegerField(default=1)
    frequency = models.IntegerField(default = 100)
    multiplier = models.IntegerField()
    buyCost = models.IntegerField()
    sellValue = models.IntegerField(blank=True, null=True)

    class Meta:
        abstract = True

class RandomManager(Manager):
    def get_query_set(self):
        return super(RandomManager, self).get_query_set().order_by('?')[0]

class WeaponTemplate(WeaponBase):
    objects = Manager()
    random = RandomManager()

class Weapon(WeaponBase):
    @classmethod
    def fromTemplate(cls, weaponTemplate):
        w = Weapon()
        for field in w._meta.fields:
            setattr(w, str(field.name), getattr(weaponTemplate, field.name))
        return w