'Django query set to display particular field on webpage
I am trying to display the variants(field) that are related to the model RecordVariant on my webpage i have queryset on my view default how can i change my queryset or get queryset method to display variants that are related to particular record.
class RecordVariant(models.Model):
variants = models.ForeignKey(Variant_model, related_name = 'records', on_delete =
models.CASCADE)
class Variant(models.Model):
name = models.CharField(max_length = 23, blank=True, null=True)
class RecordVariantListAPIView(RecordMixin, ListAPIView):
lookup_url_kwarg = 'record_id'
serializer_class = RecordVariantSerializer
permission_classes = [IsAuthenticated]
pagination_class = StandardResultsSetPagination
filter_backends = (filters.OrderingFilter,)
queryset = RecordVariant.objects.all()
ordering = 'variants'
ordering_param = 'ordering'
ordering_fields = (
'variants',
)
def get_total_queryset(self):
queryset = (
super()
.get_queryset()
.filter(record=self.record)
)
Solution 1:[1]
in foreignkey relations the child should be the one with foreginkey field. meaning your Variant model class should have this field
class Variant(models.Model):
name = models.CharField(max_length = 23, blank=True, null=True)
records = models.ForeignKey(RecordVariant, related_name = 'records',
on_delete = models.CASCADE)
class RecordVariant(models.Model):
pass
and for the serializers
class Variant(serializers.ModelSerializer):
class Meta:
model = Variant
fields = "['name']"
class RecordVariant(serializers.ModelSerializer):
records = VariantSerializer(many=True)
class Meta:
model = RecordVariant
fields = '__all__'
the view
class RecordVariantListAPIView(ListAPIView):
serializer_class = RecordVariantSerializer
permission_classes = [IsAuthenticated]
queryset = RecordVariant.objects.all()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |