How do you make one request for all related objects?



  • class Модель_1(models.Model): 
        поле = models.IntegerField()
    
    
    class Модель_2(models.Model):
        модель_1 = models.ForeignKey(Модель_1, related_name="модели_1")
    
    
    модели_1 = Модель_1.objects.filter(поле="значение")
    

    I've chosen models, or part of the models.

    Now, as a separate request, it's just one request and without prefetch_related, to select all the Models2 that are linked to the models already selected.

    It's just a thought to try to use the values... for the sample. You can't download the bound tables.



  • ids = модели_1.values_list('id', flat=True)
    
    #или, если queryset уже выбран из базы
    ids = [o.id for o in модели_1]
    
    Модель_2.objects.filter(модель_1_id__in=ids)
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2