Skip to content

Instantly share code, notes, and snippets.

@Buzovskiy
Created March 3, 2022 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Buzovskiy/531a25c1d472b32c26f3d08959c5f18f to your computer and use it in GitHub Desktop.
Save Buzovskiy/531a25c1d472b32c26f3d08959c5f18f to your computer and use it in GitHub Desktop.
Django reverse foreign key with prefetch related
# models.py
class WareHouse(models.Model):
address = models.CharField(max_length=255, null=True, unique=True)
def __str__(self):
return self.address
class Product(models.Model):
article = models.CharField(max_length=255, null=True, unique=True)
productwarehouse = models.ForeignKey(WareHouse, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.article
# views.py
from .models import WareHouse
for warehouse in WareHouse.objects.prefetch_related('product_set').all():
for product in warehouse.product_set.all():
print(product.article)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment