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