Python 如何删除Django模型中的记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3805958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:49:21  来源:igfitidea点击:

How to delete a record in Django models?

pythondjangodjango-models

提问by user426795

I want to delete a particular record. Such as

我想删除一个特定的记录。如

delete from table_name where id = 1;

How can I do this in a django model?

我怎样才能做到这一点django model

回答by Wolph

There are a couple of ways:

有几种方法:

To delete it directly:

直接删除:

SomeModel.objects.filter(id=id).delete()

To delete it from an instance:

要从实例中删除它:

instance = SomeModel.objects.get(id=id)
instance.delete()

回答by VicX

Wolph provided a good answer focused codes. Let me just paste official dochere, for people's reference.

Wolph 提供了一个很好的答案集中代码。让我在这里粘贴官方文档,供人们参考。

回答by Milad Khodabandehloo

MyModel.objects.get(pk=1).delete()

this will raise exception if the object with specified primary key doesn't exist because at first it tries to retrieve the specified object.

如果具有指定主键的对象不存在,这将引发异常,因为它首先尝试检索指定的对象。

MyModel.objects.filter(pk=1).delete()

this wont raise exception if the object with specified primary key doesn't exist and it directly produces the query

如果具有指定主键的对象不存在并且直接生成查询,则不会引发异常

DELETE FROM my_models where id=1

回答by lilhamad

If you want to delete one item

如果要删除一项

wishlist = Wishlist.objects.get(id = 20)
wishlist.delete()

If you want to delete all items in Wishlist for example

例如,如果您想删除愿望清单中的所有项目

Wishlist.objects.all().delete()

回答by siful islam

if you want to delete one instance then write the code

如果要删除一个实例,则编写代码

delet= Account.objects.get(id= 5)
delet.delete()

if you want to delete all instance then write the code

如果要删除所有实例,请编写代码

delet= Account.objects.all()
delete.delete()