如何在复杂的django模型中使用自定义字段?

时间:2015-07-16 17:41:02

标签: django python-2.7 django-models

我想定义一个模型,其中一个字段可以是其他定义模型之一。 我有三个模型,如飞机,火车和公共汽车。每个模型都有自己的字段。 例如

class Train(models.Model):
    id = models.AutoField(primary_key=True)
    train_name = models.CharField(max_length=200)
    date_of_journey= models.DateField()
    from_station = models.CharField(max_length=4)
    to_station = models.CharField(max_length=4)
    class_selection = models.CharField(max_length=6, choices=class_choices)

class Plane(models.Model):
    id = models.AutoField(primary_key=True)
    date_of_journey= models.DateField()
    from_airport = models.CharField(max_length=4)
    to_airport = models.CharField(max_length=4)
    plane_model = models.CharField(max_length=10)

class Bus(models.Model):
    id = models.AutoField(primary_key=True)
    date_of_journey= models.DateField()
    from_city = models.CharField(max_length=100)
    to_city = models.CharField(max_length=100)

我想创建一个名为Trip的模型,它具有以下结构:

class Trip(models.Model):
    id = models.AutoField(primary_key=True)
    trip_name = models.CharField(max_length=250)
    reason = models.CharField(max_length=30, null=True, blank=True)
    individual_journey = JourneyType(oneToManyField)

旅行可以有多个单独的旅程,每次旅行应该是公共汽车旅行,火车旅行或飞机旅行。

1 个答案:

答案 0 :(得分:0)

from django.core.exceptions import ValidationError

class JourneyType(models.Model):
    bus = models.ForeignKey('Bus', blank=True, null=True)
    train = models.ForeignKey('Train', blank=True, null=True)
    plain = models.ForeignKey('Plain', blank=True, null=True)

    def clean(self):
        if not (self.bus or self.train or self.plain) or \
                (self.bus and self.train) or (self.bus and self.plain) or \
                (self.train and self.plain):
            raise ValidationError('You should specify (only) one journey type')

    def __unicode__(self):
        if self.bus:
            return 'Bus id={0}'.format(self.bus)
        elif self.train:
            return 'Train id={0}'.format(self.train)
        else:
            return 'Plain id={0}'.format(self.plain)

class Trip(models.Model):
    # ...
    individual_journey = models.ForeignKey('JourneyType')