Search code examples
djangoforeign-keysdjango-related-manager

Django filter table by foreign keys in related manager column


I have three models in my Django application:

class MainData(models.Model):
    # bunch of fields

class Label(models.Model):
    label = models.CharField(max_length=512, null=True, unique=True)

class MapData(models.Model):
    labelMatch = models.ForeignKey(Label, on_delete=models.CASCADE)
    mainMatch = models.ForeignKey(MainData, on_delete=models.CASCADE)

Through my application, I have the user enter a label in a search box. What I would like to do is return the MainData rows whos' MapData.label_match field is the entry in Label.

For example, say the user enters the string 'main32' into the search box. My current thought is to first find Label rows that match 'main32', then use the RelatedManager labelmatch_set to get all of the MapData rows that MapData.mainMatch points to. So if there are 10 MapData rows whose labelMatch points to a Label entry with label='main32', I then want to retrieve all 10 MainData rows that the foreign key mainMatch points to.

Hopefully I explained that ok. I have gotten to:

matching_label_rows = Label.objects.filter(input)
matching_main_data_rows = matching_label_rows.mainMatch_set.????

How can I retrieve the pointed to MainData rows from matching_label_rows.mainMatch_set? And can this operation be done as a one-liner?


Solution

  • Instead of finding the matching Labels first, you can filter MainData on the mapdata__labelMatch relationship:

    matching_main_data_rows = MainData.objects.filter(mapdata__labelmatch__label__icontains=input)
    

    Lookups that span relationships