Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

query foreignkey field from other field which is foreign key to other

I have model 3 models model 1 2 and 3 i need to access model 1 from model 3 model 2 has foreign key relation with model 1 and model 3 to model 2 how can access model 3 to model 1

class Record(models.Model):
    name = model.CharField(max_length=255)

class Task(model.Model):
    name = models.CharField('Record')
    record = models.ForeignKey(max_length, related_name='tasks')

class Subtask(models.Model):
    name = models.CharField()
    subtask_of = models.Foreignkey('Task', related_name=subtasks)

I need to access the record name from Subtask how can i achieve that

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To filter Subtask by the related Record.name use double-underscores to follow the relationships

exact_matches = SubTask.objects.filter(subtask_of__record__name='foo')
partial_matches = SubTask.objects.filter(subtask_of__record__name__icontains='foo')

To access Record.name follow the foreign keys from your Subtask object

subtask_obj.subtask_of.record.name
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading