M2M fields supported

This commit is contained in:
Tom Christie 2012-10-03 16:08:20 +01:00
parent 09f2267601
commit a366d6e612
3 changed files with 18 additions and 5 deletions

View File

@ -180,6 +180,10 @@ class RelatedField(Field):
Subclass this and override `convert` to define custom behaviour when
serializing related objects.
"""
def __init__(self, *args, **kwargs):
self.queryset = kwargs.pop('queryset', None)
super(RelatedField, self).__init__(*args, **kwargs)
def field_to_native(self, obj, field_name):
obj = getattr(obj, self.source or field_name)
if obj.__class__.__name__ in ('RelatedManager', 'ManyRelatedManager'):

View File

@ -246,7 +246,9 @@ class DocumentingHTMLRenderer(BaseRenderer):
serializers.DateField: forms.DateField,
serializers.EmailField: forms.EmailField,
serializers.CharField: forms.CharField,
serializers.BooleanField: forms.BooleanField
serializers.BooleanField: forms.BooleanField,
serializers.PrimaryKeyRelatedField: forms.ChoiceField,
serializers.ManyPrimaryKeyRelatedField: forms.ModelMultipleChoiceField
}
# Creating an on the fly form see: http://stackoverflow.com/questions/3915024/dynamically-creating-classes-python
@ -257,10 +259,16 @@ class DocumentingHTMLRenderer(BaseRenderer):
serializer = view.get_serializer(instance=obj)
for k, v in serializer.get_fields(True).items():
print k, v
if v.readonly:
continue
kwargs = {}
if getattr(v, 'queryset', None):
kwargs['queryset'] = getattr(v, 'queryset', None)
try:
fields[k] = field_mapping[v.__class__]()
fields[k] = field_mapping[v.__class__](**kwargs)
except KeyError:
fields[k] = forms.CharField()

View File

@ -351,9 +351,10 @@ class ModelSerializer(RelatedField, Serializer):
"""
Creates a default instance of a flat relational field.
"""
queryset = model_field.rel.to._default_manager # .using(db).complex_filter(self.rel.limit_choices_to)
if isinstance(model_field, models.fields.related.ManyToManyField):
return ManyPrimaryKeyRelatedField()
return PrimaryKeyRelatedField()
return ManyPrimaryKeyRelatedField(queryset=queryset)
return PrimaryKeyRelatedField(queryset=queryset)
def get_field(self, model_field):
"""
@ -367,7 +368,7 @@ class ModelSerializer(RelatedField, Serializer):
models.EmailField: EmailField,
models.CharField: CharField,
models.CommaSeparatedIntegerField: CharField,
models.BooleanField: BooleanField
models.BooleanField: BooleanField,
}
try:
return field_mapping[model_field.__class__]()