如何根据从另一个table数据中获取的id获取table数据?姜戈

How to get table data based on id which obtains from another table data? Django

观看次数

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 = Vehicles.objects.filter(id=vehicles.vehicle_id)  # Not Working

如何从 table 中获取数据,其多个 ID 已被另一个 table 获取?

型号

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

class Vehicles(models.Model):
    id = models.AutoField(primary_key=True)
    vehicle_number = models.IntegerField()
    name = models.CharField(max_length=255)
    slug = models.SlugField(blank=True, null=True, unique=True)


class CompanyContainVehicles(models.Model):
    id = models.AutoField(primary_key=True)
    company_id = models.ForeignKey(Company, on_delete=models.CASCADE)
    vehicle_id = models.ForeignKey(Vehicles, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True, blank=True)

以上是我的 table 详细信息,我需要从 table Vehicles 获取所有车辆,这些车辆是从 CompanyContainVehicle table 获得的(定义哪个公司选择哪个车辆)基于company_id 从 table 公司获取,其中包含公司的详细信息。

您可以过滤:

Vehicles.objects.filter(<strong>companycontainvehicles__company_id=company_id</strong>)

这里你的 companycontainvehicles 基本上相当于 ManyToManyField。您可以跨越 VehicleCompany 之间的 many-to-many 关系:

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,
        <strong>through='CompanyVehicle'</strong>,
        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)

然后你可以过滤:

Vehicle.objects.filter(<strong>companies=company_id</strong>)

Note: normally a Django model is given a singular name, so Vehicle instead of Vehicles.


Note: Normally one does not add a suffix _id to a ForeignKey field, since Django will automatically add a "twin" field with an _id suffix. Therefore it should be company, instead of company_id.