如何删除django中的对象?
How to delete object in django?
enter image description here
@csrf_exempt
def ajax_owner_delete(request, pk):
product = Product.objects.get(pk=pk)
product.delete()
return HttpResponse(status=200)
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products', null=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, db_index=True, null=True)
slug = models.SlugField(max_length=200, db_index=True, null=True)
sell_price = models.DecimalField(max_digits=10, decimal_places=0, null=True)
prime_cost = models.DecimalField(max_digits=10, decimal_places=0, null=True)
usd_price = models.DecimalField(max_digits=10, decimal_places=0, null=True)
stock = models.PositiveIntegerField(verbose_name='stock', null=True)
created = models.DateTimeField(auto_now_add=True, null=True)
updated = models.DateTimeField(auto_now=True, null=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_detail',
args=[self.id, self.slug])
我正在这样做,它删除了模型的每个字段,但对象仍然存在(看图片)
试试这个:
def ajax_owner_delete(request, pk):
product = Product.objects.get(id=pk)
product.delete()
return HttpResponse(status=200)
enter image description here
@csrf_exempt
def ajax_owner_delete(request, pk):
product = Product.objects.get(pk=pk)
product.delete()
return HttpResponse(status=200)
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products', null=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, db_index=True, null=True)
slug = models.SlugField(max_length=200, db_index=True, null=True)
sell_price = models.DecimalField(max_digits=10, decimal_places=0, null=True)
prime_cost = models.DecimalField(max_digits=10, decimal_places=0, null=True)
usd_price = models.DecimalField(max_digits=10, decimal_places=0, null=True)
stock = models.PositiveIntegerField(verbose_name='stock', null=True)
created = models.DateTimeField(auto_now_add=True, null=True)
updated = models.DateTimeField(auto_now=True, null=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_detail',
args=[self.id, self.slug])
我正在这样做,它删除了模型的每个字段,但对象仍然存在(看图片)
试试这个:
def ajax_owner_delete(request, pk):
product = Product.objects.get(id=pk)
product.delete()
return HttpResponse(status=200)