Home > database >  How to get table data (including child table and sub child data) based on id which obtains from anot
How to get table data (including child table and sub child data) based on id which obtains from anot

Time:03-20

views

company = Company.objects.get(id = company_id)  # getting input from django urls (<int:company_id>)
vehicles = CompanyContainVehicles.objects.filter(company_id=company.id)  # Give all rows having same id (company.id)
all_vehicles = Vehicle.objects.filter(companies=company)  # Gives all row with id provide by company
all_vehicles_parts = VehiclePart.objects.filter(__________) # Not Working

models

class Company(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(blank=True, null=True, unique=True)
    description = models.TextField()

class Vehicle(models.Model):
    vehicle_number = models.IntegerField()
    name = models.CharField(max_length=255)
    slug = models.SlugField(blank=True, null=True, unique=True)
    companies = models.ManyToManyField(
        Company,
        through='CompanyVehicle',
        related_name='companies'
    )

class CompanyVehicle(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

class VehiclePart(models.Model):
    id = models.AutoField(primary_key=True)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
    type = models.ForeignKey(PartType, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True, blank=True)

How do I get VehiclePart's with their Vehicle? (I think I will give all the data in a variable and we should divide it and add it with their Vehicle). Also, what can we do to access data if VehiclePart contains a child class named VehiclePartDetail?

CodePudding user response:

I think I will give all the data in a variable and we should divide it and add with their Vehicle.

You don't have to. Django can read ForeignKey relations in reverse. You can query with:

qs = Vehicle.objects.prefetch_related('vehiclepart_set')

then you can enumerate over the queryset, and for each Vehicle object, access this with .vehiclepart_set.all(). For example:

for item in qs:
    print(vehicle_name)
    for part in item.vehiclepart_set.all():
        print(part.id)
  • Related