考虑这些伪模型:
class Category(models.Model):
name = models.CharField()
class Product(models.Model):
name = models.CharField()
code = models.CharField()
category = models.ForeignKey(Category)
price = models.DecimalField()
stock = models.IntegerField()
class AlternativeProduct(Product):
original_product = models.ForeignKey(Product, related_name="alternative", editable=False)
我想使用内联来快速添加产品及其替代选项,而无需键入重复数据(仅限代码,库存和价格差异)。
admin.py
class AlternativeProductInline(admin.TabularInline):
model = AlternativeProduct
formset = AlternativeProductInlineFormset
fk_name = "original_product"
fields = ["code", "price", "in_stock"]
max_num = 1
extra = 0
class ProductAdmin(admin.ModelAdmin):
form = ProductAdminForm
inlines = [AlternativeProductInline]
当然,这会引发ValidationError
,因为AlternativeProduct
缺少category
。
现在我可以设置一个默认值来修复它:
class Product(models.Model):
name = models.CharField()
code = models.CharField()
category = models.ForeignKey(Category, default=1)
price = models.DecimalField()
stock = models.IntegerField()
但除了这个id可能不存在之外,它还需要纠正。有没有其他方法(除了Javascript)将正版产品的类别值复制到替代内联产品' 引擎盖下 '
我试图更改admin_view,但它变得很乱,也许自定义视图会是一个很好的解决方案,虽然javascript是一种耗时较少的方法。
答案 0 :(得分:0)
Javascript似乎是实现这一目标的简单方法。
$(document).ready(function(){
$('#alternative-group thead th:nth-child(2)').hide();
$('#alternative-group tbody td:nth-child(1) p').hide();
$('#alternative-group tbody td:nth-child(3)').hide();
$('#id_alternative-0-category').hide();
var product_category = $('#id_category option:selected').val();
$('#id_alternative-0-category').val(product_category);
$("#id_category").change(function() {
product_category = $('#id_category option:selected').val();
$('#id_alternative-0-category').val(product_category);
});
});