简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM