问题:如何在Django模型中删除记录?

我要删除特定记录。如

delete from table_name where id = 1;

我怎么能做到这一点django model

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?


回答 0

有两种方法:

要直接删除它:

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

要从实例中删除它:

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

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()

回答 1

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

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

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

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

DELETE FROM my_models where id=1
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

回答 2

如果要删除一项

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

例如,如果要删除收藏夹中的所有项目

Wishlist.objects.all().delete()

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()

回答 3

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

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

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

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

if you want to delete one instance then write the code

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

if you want to delete all instance then write the code

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

回答 4

沃尔夫提供了一个很好的答案集中代码。让我在这里粘贴官方文档,以供大家参考。

Wolph provided a good answer focused codes. Let me just paste official doc here, for people’s reference.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。