3

我正在尝试在 Django 中创建一些映射到标准 Django 类型的类型。自定义模型字段文档进入复杂案例;我只想用一堆方便的方法从一个类中存储一个基本的 Django 类型。

例如,如果我要存储扑克牌,我想要这样的东西:

class Card(object):
    """ A playing card.  """
    def as_number(self):
        """ returns a number from 1 (Ace of Clubs) and 52 (King of Spades)."""
        return self.number + self.suit_rank() * 13
    def __unicode(self): ...
    def is_highest(self, other_cards, trump=None):...
    def __init__(self, number, suit):  ...
     ...

我希望我的模型具有以下内容:

class my_game(models.Model):
    ante = models.IntegerField()
    bonus_card = Card()   # Really stored as an models.IntegerField()
    ....

我期待答案看起来像从正确的类型继承,为卡添加一些特别命名的 get/store 字段,并重命名init ()。有没有人有示例代码或更好的文档?

4

3 回答 3

4

我会用 Django 的 PositiveIntegerField 的子类来做到这一点:

from django.db import models

class Card(object):
    """The ``Card`` class you described."""
    ...

class CardField(models.PositiveIntegerField):
    __metaclass__ = models.SubfieldBase

    def get_db_prep_value(self, value):
        """Return the ``int`` equivalent of ``value``."""
        if value is None: return None
        try:
            int_value = value.as_number()
        except AttributeError:
            int_value = int(value)
        return int_value

    def to_python(self, value):
        """Return the ``Card`` equivalent of ``value``."""
        if value is None or isinstance(value, Card):
            return value
        return Card(int(value))

get_db_prep_value方法负责转换value为适合与数据库交互的东西,在本例中为 anintNone.

to_python方法执行相反的操作,转换valueCard. 就像以前一样,您需要处理None作为值的可能性。使用SubfieldBase确保to_python每次将值分配给字段时都会调用它。

于 2008-12-02T20:27:56.563 回答
1

为什么您不能执行以下操作?

class Card(models.Model):
    """ A playing card.  """
    self.suit = models.PositiveIntegerField()
    self.rank = models.PositiveIntegerField( choices=SUIT_CHOICES )
    def as_number(self):
        """ returns a number from 1 (Ace of Clubs) and 52 (King of Spades)."""
        return self.number + self.suit * 13
    def __unicode__(self):
        return ...
    def is_highest(self, other_cards, trump=None):...

当然,这很简单,并且很适合 Django 自然地做的事情。

于 2008-12-02T19:55:40.733 回答
0

不要害怕根据自己的需要调整 Django 中的模型类。他们没有什么神奇之处。我想这是这段代码的正确位置:在模型中。

于 2008-12-02T20:14:58.960 回答