django模型实例编辑

时间:2014-03-06 08:52:00

标签: python django django-models

我有3个模型设置如下:

#models.py
class Room(models.Model):
    room_number = models.CharField(max_length=20, primary_key=True, null=False, blank=False)
    isolation_status = models.BooleanField()


class Treatment(models.Model):
    room_number = models.ForeignKey(Room, primary_key=True)
    treated = models.BooleanField()

class Isolation(models.Model):
    room_number = models.ForeignKey(Room, primary_key=True)

创建新的Treatment对象时,我需要做的是将Room.isolation_status字段设置为False。

#views.py
class AddTxView(FormView):
    template_name = 'addtx.html'
    form_class = TxForm
    success_url = '/rooms/addtx/'

def update_iso(self, form):
    instance = Room.objects.get(room_number=room_number)
    instance.isolation_status = False

def form_valid(self, form):
    save_it = form.save(commit=False)
    save_it.save()
    return super(AddTxView, self).form_valid(form)

#forms.py
class TxForm(forms.ModelForm):
    class Meta:
        model = Treatment

我什么时候应该调用update_iso函数?保存()之后?我是否应该使用基于类的视图

2 个答案:

答案 0 :(得分:1)

在保存治疗对象之前,您可以这样做:

form_obj = form.save(commit=False)
form_obj.room_number.isolation_status = False
form_obj.save()

答案 1 :(得分:0)

您可以在模型中设置此项。每当您保存治疗时,检查它是否是新的。如果是,请将room_number的isolation_status设置为false。

#models.py
class Room(models.Model):
    room_number = models.CharField(max_length=20, primary_key=True, null=False, blank=False)
    isolation_status = models.BooleanField()


class Treatment(models.Model):
    room_number = models.ForeignKey(Room, primary_key=True)
    treated = models.BooleanField() 

    def save(self, *args, **kwargs):
        is_new = False
        if self.pk is None:
            is_new = True
        super(Treatment,self).save(*args, **kwargs)
        if is_new:
            self.room_number.isolation_status = False
            self.room_number.save()

class Isolation(models.Model):
    room_number = models.ForeignKey(Room, primary_key=True)

通过这样做,无论何时添加治疗(无论是在您的视图中还是在管理员中),它都会起作用。