我在这里有一些疑问...

想象一下,我有3个班级:

class CarSpec(models.Model):
    x = models.IntegerField(default=20)
    y = models.CharField(max_length=100, blank=True)
    z = models.CharField(max_length=50, blank=True)
    chassis = models.ForeignKey(Chassis, unique=True, limit_choices_to={'type':'A'})
    car_brand = models.CharField(max_length=100, blank=True)
    car_model = models.CharField(max_length=50, blank=True)
    number_of_doors = models.IntegerField(default=2)

class MotoSpec(models.Model):
    x = models.IntegerField(default=20)
    y = models.CharField(max_length=100, blank=True)
    z = models.CharField(max_length=50, blank=True)
    chassis = models.ForeignKey(Chassis, unique=True, limit_choices_to={'type':'C'})
    motor_brand = models.CharField(max_length=100, blank=True)
    motor_model = models.CharField(max_length=50, blank=True)
    powered_weels = models.IntegerField(default=1)

class Chassis(models.Model):
    name = models.CharField(max_length=50, blank=False)
    type = models.CharField(max_length=2, choices = GAME_TYPES, default="A")

GAME_TYPES = (('A', 'Car'),('B', 'Truck'),('C', 'Motorcycle'))


我正在使用这3个类,但是在我的应用程序中,我必须一直检查机箱类型,以便对每种情况应用一些业务规则...
我认为这不是正确的方法。所以我计划了这一点:

class Spec(models.Model):
    x = models.IntegerField(default=20)
    y = models.CharField(max_length=100, blank=True)
    z = models.CharField(max_length=50, blank=True)

    class Meta:
        abstract = True


并具有两个子类:

class CarSpec(Spec):
    chassis = models.ForeignKey(Chassis, unique=True, limit_choices_to={'type':'A'})
    car_brand = models.CharField(max_length=100, blank=True)
    car_model = models.CharField(max_length=50, blank=True)
    number_of_doors = models.IntegerField(default=2)

class MotoSpec(Spec):
    chassis = models.ForeignKey(Chassis, unique=True, limit_choices_to={'type':'C'})
    motor_brand = models.CharField(max_length=100, blank=True)
    motor_model = models.CharField(max_length=50, blank=True)
    powered_weels = models.IntegerField(default=1)

class Chassis(models.Model):
    name = models.CharField(max_length=50, blank=False)
    type = models.CharField(max_length=2, choices = GAME_TYPES, default="A")

GAME_TYPES = (('A', 'Car'),('B', 'Truck'),('C', 'Motorcycle'))


好的,直到一切正常,在与以前的类一起使用的我的应用程序中没有进行任何更改,并且所有对象都按预期很好地保存在数据库中。

但是,我的问题仍然存在。.因为我继续实例化CarSpec和MotoSpec而不是Spec ...但是...我想一直使用Spec而不是扩展类...既然如此,我该怎么做能够实例化将Chassis传递到其init方法的Spec对象,以便从该(或其他)方法获取CarSpec或MotoSpec。

编辑重要提示:我为MotoSpec添加了power_weels属性,为CarSpec添加了number_of_doors,因为我对两个规格中的每一个都有一些特定的字段

再次编辑:在我看来,我想避免每次我弄乱Specs并将其留给其中一个涉及的类时进行类型验证。继续,我希望能够添加一个新的Spec对象,而不必担心更改我的视图。

# CarSpec
if game_type == "A":
    stuff = CarSpec.restore_state(request, game_session)
# MotoSpec
elif game_type == "C":
    stuff = MotoSpec.restore_state(request, game_session)


编辑:我在我的Spec类上添加了restore_state,但是后来我认为我发现了一些与循环导入有关的问题。OMG ..这使我丧命。我有.NET背景,而python在这些方面对我来说并不容易:

最佳答案

将底架,品牌和模型属性添加到Spec类,然后对CarSpec和MotoSpec类使用proxy models,也许添加诸如car_brand(),motor_brand()等方法。

09-26 05:19