我有内联,它显示contenttype
模型的数据,因此我会看到content_type
和object_id
字段而不是真实对象。我可以exclude
这些字段 - 这不是问题,但我也希望在下拉列表中将另一个selected
作为Places
的真实对象。谁能告诉我,我怎么能这样做?
型号:
class Criterias(models.Model):
name = ...
class Places(models.Model):
name = ...
class PlacesToCriterias(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
criteria_group = models.ForeignKey(Criterias)
管理:
class CriteriaPlacesInlineAdmin(admin.TabularInline):
model = PlacesToCriterias
class CriteriasAdmin(admin.ModelAdmin):
inlines = [CriteriaPlacesInlineAdmin]
admin.site.register(Criterias, CriteriasAdmin)
我可以添加CriteriaPlacesInlineAdmin
一个form
,例如:
class CriteriaPlacesChoicesFieldForm(forms.ModelForm):
places = forms.ModelChoiceField(PlaceTypesGroups.objects.all(), label='place')
但是如何通过\添加object_id
添加到此表单\查询以便选择'放在下拉列表中?
答案 0 :(得分:1)
找到解决方案。
将表单添加到admin.TabularInline
:
class CriteriaPlacesInlineAdmin(admin.TabularInline):
model = PlacesToCriterias
form = CriteriaPlacesChoicesFieldForm # <- ADDED FORM
class CriteriasAdmin(admin.ModelAdmin):
inlines = [CriteriaPlacesInlineAdmin]
admin.site.register(Criterias, CriteriasAdmin)
形式:
class CriteriaPlacesChoicesFieldForm(forms.ModelForm):
ct_place_type = ContentType.objects.get_for_model(PlaceTypesGroups)
object_id = forms.ModelChoiceField(PlaceTypesGroups.objects.all(), label='places')
content_type = forms.ModelChoiceField(ContentType.objects.all(), initial=ct_place_type, widget=forms.HiddenInput())
def clean_object_id(self):
return self.cleaned_data['object_id'].pk
def clean_content_type(self):
return self.ct_place_type