django, как использовать prefetch_related () для извлечения related_name иностранного ключа - PullRequest
0 голосов
/ 11 ноября 2019

django, как использовать prefetch_related () для извлечения related_name иностранного ключа


class B(models.Models):
    pass

class A(models.Models):

    b = models.ForeignKey(B)


class C(models.Models):
    b = models.ForeignKey(B, related_name='related_c')

Ожидаемый результат: я пытался вот так, но не смог


a_data = A.objects.prefetch_related('b__related_c')

for a in a_data:
    all_c_by_b = a.b.related_c.all()

    c_obj = all_c_by_b.first()
    # i dont want hit database
    print(c_obj)

1 Ответ

0 голосов
/ 11 ноября 2019
    You need to write your query like this:-

    A.objects.all().prefetch_related('b') # this is how you can use prefetch_related

    If you want to get all the C model record, then the query is :-

    c_result = C.objects.all()

    #then you can get all the B model data from the same query result

    b_data = c_result.related_c.all() # here is how you can get all the B model records

So, accordingly you have to write or design your model classes
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...