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?
Instead of finding the matching Label
s first, you can filter MainData
on the mapdata__labelMatch
relationship:
matching_main_data_rows = MainData.objects.filter(mapdata__labelmatch__label__icontains=input)