How do I get related data (foreign)

class Product(models.Model):        
    title = models.CharField(max_length=250)
    description = models.TextField()
    slug = models.SlugField(null=False, blank=False)
    created = models.DateTimeField(auto_now_add=True)        

class Reseller(models.Model):
    name = models.CharField(max_length=250)
    url = models.URLField(max_length=250)
    phone = models.CharField(max_length=50, default='')

class Item(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    reseller = models.ForeignKey(Reseller, on_delete=models.CASCADE)        
    price = models.PositiveIntegerField(default=0)

How do I get a product’s resellers ?

I have in my I have :

product = get_object_or_404(Product, slug=slug)

I want to get the list of resellers as a dictionary

I think I got it. Let me know if I am wrong.

items = Item.objects.filter(
return render(request, 'product/view.html', { 'product': product, 'items' : items } )

i think u haven’t got a list of resellers but list of items. of course there is a reseller id. to get the list of resellers try this:

resellers = [item.reseller for item in product.item_set.select_related("reseller")]


resellers = [item.reseller for item in product.item_set.all()]

first one will guarantee better performance - less hits to db. but both commands will return lists of resellers:

[<Reseller: Reseller object (1)>, <Reseller: Reseller object (2)>, <Reseller: Reseller object (3)>]

there is no need to instance Item objects - my comprehension list follows rellationship backward (more here). it is easy to access reseller with for loop. for example:

for reseller in ressellers: 

simillary u will have such acces in templates when u pass a list during render:

return render(request, 'product/view.html', { 'product': product, 'resellers' : resellers } )

if u want to have only items it’s nice to use backward look up as well. very clean method:

items = product.item_set.all()

From where did you get item_set.select_related ?

check out this: u can use select_related() with any queryset of objects.