Created
March 3, 2022 20:57
-
-
Save Buzovskiy/531a25c1d472b32c26f3d08959c5f18f to your computer and use it in GitHub Desktop.
Django reverse foreign key with prefetch related
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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