我有2个django模型 - 主要(产品)和链接细节(PhysicalProperty是通过其他模型ProductMetricals的多对多链接)。
在主要型号产品中,我编写了post_save接收器,详细检查和清理数据。
如果我尝试
Product.save()
来自IDLE,它运作正常。
但如果我在Admin表单中更改并保存主要产品,我就会遇到异常
Select a valid choice. That choice is not one of the available choices
我尝试调试它,但钢铁不知道 - 为什么管理员会引发异常?
这是一个代码
models.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")
admin.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)
如果我创建了一些属性,创建产品,向产品添加一个属性,然后更改产品名称并保存 - 我得到了例外
来自 ProductMetricals.objects.filter(product = instance).delete()
的异常(我认为)答案 0 :(得分:1)
您的问题在于Product上的post_save挂钩。在ProductAdmin中保存产品时,会调用save_model(),然后调用save_related()。这反过来调用带有ProductMetricals的formset的save_formset,其中包含现在已删除的ProductMetricals的键。它现在无效(因为您在保存产品时将其删除了。)
我遇到了类似的问题,在内联中删除了与管理视图中另一个内联的关系。我最终为我的外键关系设置on_delete = models.SET_NULL,因为默认情况下Django cascade删除。另一种选择是手动覆盖formset。
它看起来类似于bug #11830
中讨论的内容