如何删除管理中的对象并保留父级?
我有以下问题:
class Gift(models.Model):
name = models.CharField(max_length=255,default='')
class ProblematicGift(Gift):
# it does not help gift_ptr = models.OneToOneField(Gift, parent_link=True, default=None, null=True, blank=True, on_delete=models.DO_NOTHING)
notes = models.CharField(max_length=255,default='')
如何在管理界面中删除 ProblematicGift 的对象并保留 Gift 的对象?
简化的背景:自动选择有问题的礼物并将其添加到表中,管理员在其中查看它,修复礼物并删除有问题的礼物
I have following problem:
class Gift(models.Model):
name = models.CharField(max_length=255,default='')
class ProblematicGift(Gift):
# it does not help gift_ptr = models.OneToOneField(Gift, parent_link=True, default=None, null=True, blank=True, on_delete=models.DO_NOTHING)
notes = models.CharField(max_length=255,default='')
How I can delete the object of ProblematicGift in admin interface and keep the object of Gift ?
Simplified background: Automat select problematic gift and add it to table, where admin look at it, fix the gift and delete the ProblematicGift
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有三种选择:
最快和最简单的方法是基于
ProblematicGift
创建一个新的Gift
,然后删除ProblematicGift
。您可以使用抽象继承将
Gift
设为原始类型,然后将其子类化以创建ProblematicGift
以及诸如GoodGifts
之类的内容。之后的过程几乎相同:它们各自获得单独的表,因此您添加一个GoodGift
,然后删除ProblematicGift
。它与 #1 几乎相同,但语义更多一些。可能是您最好的选择:使用代理模型。您可以将布尔属性添加到“is_problematic”等形式的礼物中。然后,创建
ProblematicGift
作为Gift
的代理,在创建时自动将is_problematic
设置为 True,并覆盖管理器以仅返回带有的礼物>is_problematic
设置为 True。然后,您只需将该属性设置为 False,而不是删除ProblematicGift
,它就会保留查询集。--
编辑:将
注释
从ProblematicGift
移至Gift
。使用代理模型时,您无法向子类添加任何新字段。You have three choices:
Quickest and hackiest is to just create a new
Gift
based onProblematicGift
and then deleteProblematicGift
.You can use abstract inheritance to make
Gift
a primitive type and then subclass it to createProblematicGift
s and something likeGoodGifts
. The procedure after that is pretty much the same: they each get separate tables, so you add aGoodGift
and then delete theProblematicGift
. It's pretty much the same as #1, but a little more semantic.Is probably your best choice: using proxy models. You add an boolean attribute to gift of the form of something like 'is_problematic'. Then, create
ProblematicGift
as a proxy forGift
that automatically setsis_problematic
to True on creation, and override the manager to only return gifts withis_problematic
set to True. Then, you simply set that attribute to False instead of deletingProblematicGift
and it leaves the queryset.--
EDIT: Moved
note
fromProblematicGift
toGift
. When using proxy models, you can't add any new fields to the subclass.老实说,您犯的错误是试图从
Gift
继承。您不想为您的用例这样做。最好的方法是使 Gift 成为独立模型:
然后让 ProblematicGift 引用它:
现在您可以安全地删除 ProblematicGift。
Honestly, the mistake you're making is trying to inherit from
Gift
. You don't want to do that for your use case.The best way is to make Gift a stand-alone model:
And then have ProblematicGift reference it:
Now you can delete the ProblematicGift safely.