我有2个django模型-主(产品)和链接的细节(物理属性是多对多链接通过附加的模型ProductMetricals)。在
在主模型产品中,我编写了post_save receiver,在那里我详细检查和清理数据。在
如果我尝试
Product.save()
从空闲开始,它工作得很好。在
但如果我更改并保存在管理表单中的主产品,我有例外
^{pr2}$我试着调试它,但steel不知道-为什么管理员会引发异常?在
这是一个代码
在模型.py在
from django.db import models
# Create your models here.
class PhysicalProperty(models.Model):
shortname = models.CharField(max_length=255)
def __str__(self):
return self.shortname
class Product(models.Model):
shortname = models.CharField(max_length=255)
product_metricals = models.ManyToManyField( PhysicalProperty, through = 'ProductMetricals' )
def __str__(self):
return self.shortname
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Product)
def product_post_save(sender, instance, **kwargs):
ProductMetricals.objects.filter( product = instance ).delete()
class ProductMetricals(models.Model):
amount=models.FloatField()
product=models.ForeignKey( Product )
physicalproperty = models.ForeignKey(PhysicalProperty )
class Meta:
unique_together = ("product", "physicalproperty")
在管理员py在
from django.contrib import admin
# Register your models here.
from product.models import Product, ProductMetricals, PhysicalProperty
from django import forms
class PhysicalPropertyAdmin(admin.ModelAdmin):
list_display = ['shortname']
admin.site.register(PhysicalProperty, PhysicalPropertyAdmin)
class ProductMetricalsInline(admin.TabularInline):
model = ProductMetricals
fieldsets = [
(None, {'fields': ['physicalproperty','amount']}),
]
extra = 2
class ProductAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['shortname']}),
]
inlines = [ProductMetricalsInline]
list_display = ['shortname']
admin.site.register(Product, ProductAdmin)
如果我创建some属性,createproduct,向product添加一个one属性,然后更改product的名称并保存它-我得到了异常
例外情况(我认为)来自ProductMetricals.objects.filter(产品=实例).delete()
你的问题在于你的产品后保存挂钩。在ProductAdmin中保存产品时,将调用save_model(),然后调用save_related()。这又将使用ProductMetricals的formset调用save_formset,其中包含一个ProductMetricals的键,该键现在已被删除。它现在无效(因为您在产品上保存时删除了它)。在
我遇到了一个类似的问题,删除一个与管理视图中另一个内联有关系的内联。我最后设置了删除=models.SET_NULL对于我的外键关系,因为默认情况下Django cascade删除。另一个选择是手动覆盖表单集。在
它看起来类似于bug #11830中讨论的内容
相关问题 更多 >
编程相关推荐