Skip to content

Commit

Permalink
many to many field support
Browse files Browse the repository at this point in the history
  • Loading branch information
sheppard committed Nov 20, 2020
1 parent 67970e9 commit fa8fa59
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions rest/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,19 +199,31 @@ def get_wq_field_info(self, name, field, model=None):
child_config = {'form': []}
info['type'] = 'repeat'
info['children'] = child_config['form']
if 'initial' in child_config:
info['initial'] = child_config['initial']
for key in ('initial', 'control'):
if key in child_config:
info[key] = child_config[key]

elif isinstance(field, serializers.RelatedField):
# Foreign key to a parent model
info['type'] = 'string'
info['type'] = 'select one'
info['name'] = info['name'].replace('_id', '')
info['label'] = info['label'].replace(' Id', '')
if hasattr(field, 'queryset'):
fk = self.get_wq_foreignkey_info(field.queryset.model)
if fk:
info['wq:ForeignKey'] = fk

elif isinstance(field, serializers.ManyRelatedField):
# ManyToMany field to related model
info['type'] = 'select'
info['name'] = info['name'].replace('_id', '')
info['label'] = info['label'].replace(' Id', '')
if field.child_relation.queryset:
fk = self.get_wq_foreignkey_info(
field.child_relation.queryset.model
)
info['wq:ForeignKey'] = fk

if 'type' not in info:
info['type'] = 'string'

Expand Down Expand Up @@ -361,7 +373,11 @@ def update_id_fields(self, fields):
continue

default_field = fields[name]
auto_related_field = (serializers.Serializer, LookupRelatedField)
auto_related_field = (
serializers.BaseSerializer,
serializers.ManyRelatedField,
LookupRelatedField,
)
if not isinstance(default_field, auto_related_field):
continue

Expand All @@ -383,7 +399,7 @@ def update_id_fields(self, fields):
if name in fields:
# Update/remove DRF default foreign key field (w/o _id)
if self.is_detail and isinstance(
default_field, serializers.Serializer):
default_field, serializers.BaseSerializer):
# Nested representation, keep for detail template context
fields[name].read_only = True
else:
Expand Down Expand Up @@ -453,7 +469,10 @@ def get_label_fields(self, default_fields):
'source': name,
}
if field_kwargs.get('many', None):
label_field_kwargs['many'] = field_kwargs['many']
label_field_kwargs.update(
many=True,
read_only=True,
)
fields[name + '_label'] = serializers.StringRelatedField(
**label_field_kwargs
)
Expand Down

0 comments on commit fa8fa59

Please sign in to comment.