在django cbv中删除后执行更新查询

时间:2017-12-04 02:54:17

标签: python django

我成功删除数据后尝试更新其他表。以下是我的 class AttendeeDeleteView(DeleteView): model = Attendee success_url = reverse_lazy('index') def get_form_kwargs(self): id = self.kwargs['id'] # get value of enr Payment.objects.filter(pk=id).update(registered=0)

urls.py

在我的url(r'^delete/(?P<pk>\d+)$', AttendeeDeleteView.as_view(template_name="includes/attendee_delete.html"), name='attendee_delete',),

class Payment(models.Model):
    id = models.AutoField(primary_key=True)
    payee = models.CharField(max_length=200, blank=True, null=True)
    contact = models.CharField(max_length=200,blank=True, null=True)
    batch = models.CharField(max_length=200, null=True, blank=True)
    ticketNumber = models.CharField(max_length=200)
    ticketType = models.CharField(max_length=200, choices=TICKET_CHOICES, default='paid')
    date = models.DateField('Date Paid (MM/DD/YYYY)', max_length=200,  null=True, blank=True)
    remarks = models.CharField(max_length=200 ,blank=True, null=True)
    registered = models.BooleanField(default=False)
    def __str__(self):
        return  self.payee



class Attendee(models.Model):
    id = models.AutoField(primary_key=True)
    payment = models.OneToOneField(Payment, on_delete=models.CASCADE,  null=True, blank=True)
    name = models.CharField(max_length=200)
    batch = models.CharField(max_length=200, blank=True, null=True)
    department = models.CharField(max_length=200, choices=DEPT_CHOICES, default='')
    remarks = models.CharField(max_length=200, blank=True, null=True)

我的当前代码成功删除了该项但未能更新其他表。

我的模特

def get(self, request, *args, **kwargs):
        id = kwargs['pk']  # get value of enr
        context = Payment.objects.filter(pk=id).update(registered=0)
        return self.render_to_response(context)

更新1:

我跟着this想出了

context must be a dict rather than int.

但它返回了public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } protected override bool OnBackButtonPressed() { //Do something return base.OnBackButtonPressed(); } }

1 个答案:

答案 0 :(得分:1)

我认为def get_form_kwargs(self):没有执行,因为它用于FormMixin。但是,您也可以在get()函数中处理它。

def get(self, request, *args, **kwargs):
    attendee = self.get_object()
    Payment.objects.filter(pk=attendee.payment.pk).update(registered=0)

    context = self.get_context_data(object=attendee)
    return self.render_to_response(context)

有关详情..

,请参阅此https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/DeleteView/

修改

以下解决方案如果在使用get()方法时仍然出现问题。

from django.http import HttpResponseRedirect
....


def delete(self, request, *args, **kwargs):
    """
    Calls the delete() method on the fetched object and then
    redirects to the success URL.
    """
    self.object = self.get_object()
    success_url = self.get_success_url()

    Payment.objects.filter(pk=self.object.payment.pk).update(registered=0)

    self.object.delete()
    return HttpResponseRedirect(success_url)