当我更新具有外键

时间:2017-09-21 11:21:25

标签: python django

我在models.py档案中有这两个模型:

class Ticket(models.Model):
    name = models.CharField(max_length=50)
    description_issue = models.CharField(max_length=1000)
    pub_date = models.DateTimeField("publication date", default=timezone.now)

class PossibleSolution(models.Model):
    title = models.CharField(max_length=50)
    description_solution = models.CharField(max_length=1000)
    final = models.BooleanField()
    sol_date = models.DateTimeField("solution date", default=timezone.now)
    tickets = models.ForeignKey(Ticket, blank=True, null=True)

示例:我有一个Ticket,其中包含名称,描述和发布日期,然后我创建了一个PossibleSolution,并以我创建PossibleSolution的形式,选择相关的票证。

然后,在另一种形式中,我更新原始票证,更改它的名称,然后我丢失了我创建的PossibleSolution。

这里可以发生什么?

编辑:这是我编辑故障单的地方

class TicketForm(forms.ModelForm):
    class Meta:
        def __init__(self, *args, **kwargs):
            super(TicketForm, self).__init__(*args, **kwargs)
            self.fields['pub_date'].widget = widgets.AdminSplitDateTime()
            self.fields['closing_date'].widget = widgets.AdminSplitDateTime()
            self.fields['issuer'].widget.attrs['readonly'] = True

        model = Ticket
        fields = '__all__'
        labels = {
            'name': _('Nombre'),
            'description_issue': _('Descripción'),
            'pub_date': _('Fecha de creacion'),
            'closing_date': _('Fecha de cierre'),
            'priority': _('Prioridad'),
            'issuer': _('Creado por'),
            'category': _('Categoría')
        }
        widgets = {
            'pub_date': DateTimeWidget(attrs={'id': "pub_date"}, usel10n=True, bootstrap_version=3),
            'closing_date': DateTimeWidget(attrs={'id': "closing_date"}, usel10n=True, bootstrap_version=3),
        }

这是我有POST的视图

def ticket(request, id_ticket):
    if request.method == "POST":
        form = TicketForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            messages.success(request, 'ticket-saved')
            if id_ticket and int(id_ticket) > 0:
                # I have this because I don't know how to really modify
                Ticket.objects.get(id=id_ticket).delete()
            return redirect('index')

1 个答案:

答案 0 :(得分:3)

删除执行删除查询的行

def ticket(request, id_ticket):
    ticket = Ticket.objects.get(id=id_ticket)
    if request.method == "POST":
        form = TicketForm(request.POST, instance=ticket)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            messages.success(request, 'ticket-saved')
            return redirect('index')
    else:
        form = TicketForm(instance=ticket)
    return render(request, 'template_name', {'form':form})