Im trying to create a filter, and get the choices from the related model. Is it possible?
My models:
class Container(models.Model):
description = models.CharField(max_length=255)
class Period(models.Model):
class PeriodType(models.TextChoices):
LONG = 'long', 'Long period'
SHORT = 'short', 'Short period'
container = models.ForeignKey(to=Container, null=True, blank=True, on_delete=models.SET_NULL)
type = models.CharField(max_length=15, choices=PeriodType.choices, null=True, blank=True)
My viewset:
class ContainerFilter(django_filters.FilterSet):
type_of_period = django_filters.ModelChoiceFilter(Period.objects.all(), field_name='period__type', label='Type')
class Meta:
model = models.Container
fields = ['type_of_period',]
class ContainerModelViewSet(viewsets.ModelViewSet):
queryset = models.Container.objects.all()
lookup_field = 'id'
filter_backends = [filters.SearchFilter, django_filters.rest_framework.DjangoFilterBackend]
search_fields = ['description',]
filter_class = ContainerFilter