我正在使用py3 + django 2.x使用通用外键建立内联模型。子模型和父模型中都有一个称为“客户端”的通用值,它是链接到客户端表的外键。
添加子项时,我希望新的子项自动采用保存在其父项中的“客户端”值。我试图用谷歌搜索它的答案而没有找到解决方案...
#Filestorage management model
class ChildModel(models.Model):
object_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
of = GenericForeignKey('content_type', 'object_id')
#
fileName = models.CharField(max_length=50)
client = models.ForeignKey(ClientCtrl, on_delete=models.CASCADE)
#Filestorage management inline
class ChildModelLine(GenericTabularInline):
model = ChildModel
ct_field_name = 'content_type'
id_field_name = 'object_id'
fieldsets = (
(None, {
'fields': ('id','client','fileName',...),
}),
)
readonly_fields = ('id','client')
class ParentModelAdmin(admin.ModelAdmin):
inlines = [ChildModelLine]
...
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for instance in instances:
if not instance.pk:
instance.oper = request.user
instance.client = self.ParentModel.client
instance.save()
formset.save_m2m()
添加嵌入式项目时,我想将现有的客户价值键从父级传递给子级。