1

在我們的應用程序中,我們的模型A具有通用關係的字段,因爲它可能與兩個模型中的任意一個的實例(BC)有關。在Django中,如何從單個表單域填充泛型關係?

當填充非通用ForeignKey字段時,我們可以使用ModelChoiceField。 我們的問題是我們無法找到MultipleModelsChoiceField,它們的選擇將從BC上的查詢集填充。

如何通過儘可能多地重用現有的Django代碼來解決這個問題?

回答

2

你可以做這樣的事情:

class YourForm(forms.ModelForm): 
    your_field = forms.ChoiceField() 

    def __init__(self, *args, **kwargs): 
     super(YourForm, self).__init__(*args, **kwargs) 
     your_generic_relations_objects = list(FirtsModel.object.all()) + list(SecondModel.objects.all()) # and etc 
     object_choices = [] 
     for obj in your_generic_relations_objects: 
      type_id = ContentType.objects.get_for_model(obj.__class__).id 
      obj_id = obj.id 
      form_value = 'type:%s-id:%s' % (type_id, obj_id) 
      display_text = str(obj) 
      object_choices.append([form_value, display_text]) 
     self.fields['your_field'] = forms.ChoiceField(choices=object_choices) 

    class Meta: 
     model = YourModel 
     fields = [ 
      'your_field' # and others 
     ] 

    def save(self, *args, **kwargs): 
     object_string = self.cleaned_data['your_field'] 
     matches = re.match("type:(\d+)-id:(\d+)", object_string).groups() 
     content_type_id = matches[0] 
     object_id = matches[1] 
     content_type = ContentType.objects.get(id=content_type_id) 
     self.instance.object_id = object_id 
     self.instance.content_type = content_type 
     return super(YourForm, self).save()