简体   繁体   中英

How to write select query in django in chain of one-to-many relationship?

How to write select query in django? I have 2 one-to-may relationship

At the beginning, i am not very good at english. i am so sorry :). I have 3 tables. Driver, Car and Ride. The relationship between Driver and Car is (one-to-many: a Driver can have multiple Car. The relationship between Car and Ride is (one-to-many: a Car can have multiple Ride. I want list of drivers who have x times of rides.

My Models:

class Driver(models.Model):
    account = GenericRelation(Account, related_query_name='drivers')

class Car(models.Model):
    owner = models.ForeignKey(Driver, on_delete=None)

class Ride(models.Model):
    car = models.ForeignKey(Car, on_delete=models.CASCADE)
    request = models.OneToOneField(RideRequest, on_delete=models.CASCADE, null=False)

I expect something like this: <QuerySet [<Driver: 1>, <Driver: 2>]> which is Drivers with greater than or equal x Rides

You can count the number of Ride s per Driver , and then filter on that number, like:

from django.db.models import 

Driver.objects.annotate(
    
).filter()

We thus first annotate each Driver object with the Count(..) [Django-doc] of related Ride s, next we filter that queryset by specifying that the nrides field annotation should be greater than or equal to x , by using the __gte lookup [Django-doc] . Here x is of course the number of required rides you need to fill in (for example 5 ).

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