我是否正确设置了它?

时间:2014-01-23 04:38:24

标签: python django

我在问我是否正确设置了create方法。或者是否需要为其他两个型号添加?怎么会改变?

class PointModel(models.Model):
    x       = models.IntegerField()
    y       = models.IntegerField()
    index           = models.IntegerField()

class DatetimeRangeModel(models.Model):
    start_datetime  = models.CharField(max_length=14)
    end_datetime    = models.CharField(max_length=14)

class PlanModel(models.Model):
    data_number             = models.IntegerField()
    data_datetime_range     = models.ForeignKey(DatetimeRangeModel, blank=True, null=True, on_delete=models.SET_NULL)
    data_polygon            = models.ForeignKey(PointModel, blank=True, null=True, on_delete=models.SET_NULL)

    @classmethod
    def create(cls, data_number, data_datetime_range, data_polygon):
        plan = cls(data_number=data_number, data_datetime_range = data_datetime_range,
                    data_polygon=data_polygon)

        return plan

编辑:我更改了修复未定义的结构,并添加了一些逻辑,阻止PlanModel被删除,其中“blank = True,null = True,on_delete = models.SET_NULL”

这看起来不错吗?

1 个答案:

答案 0 :(得分:1)

查看creating objects

的文档
@classmethod
def create(cls, title):
    book = cls(title=title)
    # do something with the book
    return book

没有太多理由添加这些内容,除非您在# do something with the book行添加内容

编辑:您通常不会致电create

plan = PlanModel(data_number=1, ....)
plan.save()

或有时:

plan = PlanModel()
plan.data_number=1
...
plan.save()