Title: Update field in unrelated table by spanning relationships using Django ORM
Tags: django;python-3.x;django-models;django-orm
Question: I am using Django 3.0.4. I have 6 tables (Vehicle, Tracker, Driver, Contract, Account and Invoice). There are Many Invoices for each Account(1-M). A single Account is opened for every single Contract(1-1). Each Contract is comprised of a Driver and a Vehicle and Driver-Vehicle combination can have only 1 Contract. Each Vehicle is fitted with a single Tracker(1-1). I intend to check the status of the Invoice(I have done this already) and navigating from this particular record of Invoice I need to find the particular Vehicle inorder to update the status of the Tracker. Tracker has no relation to Invoice and select_related does not seem to work. Your assistance is appreciated.
class Vehicle(models.Model):
registration = models.CharField(max_length=7, unique = True)
make = models.CharField(max_length=16)
model = models.CharField(max_length=16)
class Tracker(models.Model):
vehicle = models.OneToOneField('Vehicle', on_delete=models.CASCADE)
msisdn = models.PositiveIntegerField()
status = models.CharField(max_length=16)
class Driver(models.Model):
first_name = models.CharField(max_length=16)
middle_name = models.CharField(max_length=16, blank=True)
last_name = models.CharField(max_length=16)
class Contract(models.Model):
vehicle = models.ForeignKey('Vehicle', on_delete=models.CASCADE)
driver = models.ForeignKey('Driver', on_delete=models.CASCADE)
start_date = models.DateTimeField(auto_now=False, auto_now_add=False)
end_date = models.DateTimeField(auto_now=False, auto_now_add=False)
class Account(models.Model):
contract = models.OneToOneField('Contract', on_delete=models.CASCADE)
weekly_amount = models.PositiveSmallIntegerField()
weeks = models.PositiveSmallIntegerField()
paid_amount = models.PositiveIntegerField()
class Invoice(models.Model):
account = models.ForeignKey('Account', on_delete=models.CASCADE)
amount = models.PositiveIntegerField()
status = models.CharField(max_length=16, choices=INVOICE_STATUS, default=UNPAID)
Comment: Are you looking for the normal Django lookups? Something like ```invoice.account.contract.vehicle.tracker``` should give you the appropriate ```Tracker```.

Comment: This has done the trick. Thanks for offering that advise.
tracker = Tracker.objects.get(vehicle__contract__account__invoice = invoice.id)



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2020:00:04/13/20', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<django><python-3.x><django-models><django-orm>', 'Title': 'Update field in unrelated table by spanning relationships using Django ORM', 'ViewCount': 15, 'id': 61184001, 'user_AboutMe': None, 'user_AccountId': 10890332.0, 'user_DisplayName': 'mdennism', 'user_Reputation': 35.0, 'user_Views': 3.0, 'user_id': 8006350.0}}