22👍
The problem comes from your queryset
: queryset = Plan.objects.all()
. None of the items in this queryset
has .group
attribute that’s why your result is empty. By default Django creates a reverse relation of the plan
ForeignKey called group_set
(unless you don’t rename it via related_name
) (this means that every plan
item in the queryset
have a group_set
attribute which is a queryset containing all the groups of this plan
). You can use this attribute in order to get a proper serialization. This means to change:
class PlanSerializer(serializers.ModelSerializer):
group_set = GroupSerializer(many=True, read_only=True)
class Meta:
model = Plan
fields = ('name', 'group_set')
If you really want to stick with group
(btw this is a very bad name for a list of groups). You can hack it with prefetch_related
like so:
queryset = Plan.objects.prefetch_related('group_set', to_attr='group')
this way every plan
item will have a group
attribute – a queryset
containing all the groups for this plan
.
2👍
Never forget to give related name for the foreign key. for eg
In models
plan = modles.ForeignKey(Plan, related_name="plan")
In Serializers
plan = PlanSerializers(many = True, read_only = True)
- Django rest framework nested viewsets and routes
- Django REST framework – multiple lookup fields?
- Django error: "'ChoiceField' object has no attribute 'is_hidden'"
- Django Tutorial: name 'HttpResponse' is not defined
- Django Allauth Custom Login Does Not Show Errors