Intersection in GeoDjango with cutting of excess parts of the polygon

I have a polygon called car and I need to make an intersection of polygons in the polygon area car and cut the excess parts of the polygon that leave the polygon area car.

explaining the code below: First I take the polygon and store it in the variable car then I check the value of a parameter of the function if its value is a it makes the intersection if not it should make the intersection cutting the parts of the polygons that are outside the polygon car but this is not happening what should I do?

def get_car_with_fire(cod, inter):
     car = CAR.objects.filter(cod__iexact=cod).first()

     car_geom = car.geom

     if inter == "a":
          fire = Fire.objects.filter(geom__intersects=car_geom)
     elif inter == "b":
          fire = Fire.objects.filter(geom__within=car_geom) #Here you must cut the ecedent parts of the polygon

I tried to use the geom__within function to return all the polygons in the area but it only returns the polygons that are 100% within car and does not perform the cut

What you need is the ST_Intersection - ST_Intersection function from PostGIS, which computes the geometric intersection of two geometries.

def get_car_with_fire(cod, inter):
    car = CAR.objects.filter(cod__iexact=cod).first()
    car_geom = car.geom

    if inter == "a":
        # This returns all fire polygons that intersect with car_geom
        fire = Fire.objects.filter(geom__intersects=car_geom)
    elif inter == "b":
        # This returns fire polygons but with their geometries cut to the car boundary
        from django.contrib.gis.db.models.functions import Intersection
        fire = Fire.objects.filter(geom__intersects=car_geom).annotate(
            intersection=Intersection('geom', car_geom)
        )
        # Now each fire object has an 'intersection' attribute containing the cut geometry

In the “b” case, this creates an annotation called intersection for each fire object that contains the geometric intersection of the fire’s geometry with the car’s geometry. You can then access this cut geometry via fire.intersection.

If you need to update the actual fire objects with their cut geometries, you would need to iterate through them and update each one:

if inter == "b":
    from django.contrib.gis.db.models.functions import Intersection
    fires = Fire.objects.filter(geom__intersects=car_geom)
    
    for fire in fires:
        # Calculate the intersection
        intersection = Intersection(fire.geom, car_geom)
        # Update the fire object with the cut geometry
        fire.geom = intersection
        # Optionally save if you want to persist these changes
        # fire.save()