_set in Django for a queryset

前端 未结 2 1722
花落未央
花落未央 2020-12-01 07:44

I\'m a bit confused how to use _set in a QuerySet in Django. For example, an object Blog b, and the object Entry related

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 08:24

    Briefly speaking:

    Suppose you have a model Car and a model Wheel. Wheel has a foreign key relationship with Car as follows:

    class Car(models.Model):
        pass
    
    class Wheel(models.Model):
        car = models.ForeignKey(Car, on_delete=models.CASCADE) # on_delete parameter is mandatory in Django 2.0
    

    Let's say w is an instance of Wheel, and c is an instance of Car:

    >>> w.car # returns the related Car object to w
    >>> c.wheel_set.all() # returns all Wheel objects related to c
    

    Detailed explanation

    Using the models defined above, a Wheel object w can get its associated Car object by accessing the car attribute: w.car.

    If a model has a ForeignKey, instances of that model will have access to the related foreign object via a simple attribute of the model.

    According to the official Django documentation:

    Django also creates API accessors for the “other” side of the relationship – the link from the related model to the model that defines the relationship.

    In this case, a Car object c has access to a list of all related Wheel objects via the wheel_set attribute: c.wheel_set.all().

    If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased. This Manager returns QuerySets, which can be filtered and manipulated.

提交回复
热议问题