Django search in one to one field

Wanna do search field by multiple fields from different classes in models. So I have model 1

class Man(models.Model):
    name = models.CharField(max_length=80)
    date = models.DateField()

And model 2

class Data(models.Model):
    man = models.OneToOneField(
                                    Man,
                                    on_delete=models.CASCADE,
                                    primary_key=True
                                    )
    data = models.JSONField(null=False)
    

And I'm trying to create search for field Man.name and then for some fields from JSON blob. My views.py

class DataList(generics.ListAPIView):
    search_fields = ['man.name']
    filter_backends = (filters.SearchFilter, )
    queryset = Data.objects.all()
    serializer_class = DataSerializer

But when I'm trying to run it I have an error cause it can't access field man.name. So how can I acces it for searching?

To access attributes from a related object you need to write using __ instead of ., so the correct version would be:

search_fields = ['man__name']

This is explained on documentation here, you can search for the section that says "You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation"

Back to Top