Home > Enterprise >  query foreignkey field from other field which is foreign key to other
query foreignkey field from other field which is foreign key to other

Time:08-26

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

CodePudding user response:

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
  • Related