Dolander
Dolander

Reputation: 49

Retrieve data from Models with Foreign Keys

I have a doubt about getting the data from another Model using ForeignKeys. I got a Salesman in a model

class Salesman(models.Model):
    name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    store = models.ForeignKey(Store, on_delete=models.CASCADE)

def __str__(self):
    return "%s" % (self.name)

Store model

class Store (models.Model):
    name= models.CharField(max_length=50)
    phone = models.IntegerField()
    contactMail = models.EmailField()

    def __str__(self):
        return "%s" % (self.name)

And a Product Model

class Product (models.Model):
    name = models.CharField(max_length=40)
    description = models.CharField(max_length=150)
    price = models.CharField(max_length=7)
    store = models.ManyToManyField(Store)


def __str__(self):
    return "%s" % (self.name)

I was trying to get the name of the Store throught the Salesman because later I need to get Products associated in the Store and i want to use the same process or something similar to populate a HTML table with Products in that specific Store.

I already got a Salesman called JohnSmith, in Store named LeBlanc. Pencil and Book are Product associated in LeBlanc

In my view:

def load_store(request):
    salesDude = Salesman.objects.filter(name='JohnSmith')
    print(salesDude)
    // <QuerySet [<Salesman: JohnSmith>]>     <- gotcha

Then I try to use the Salesman object to retrieve the ID from the Store but i'm stuck here. Forward, i need the name of the store to be recovered and used as a filter to retrieve the Products in the Store.

How can i achieve that? I'm only getting the ID and not the name. Any help will be appreciated.

Upvotes: 0

Views: 38

Answers (1)

user9727749
user9727749

Reputation:

Try:

def load_store(request):
    salesDude = Salesman.objects.filter(name='JohnSmith')
    print (salesDude)
    store = salesDude.store
    print (store)
    products = Product.objects.filter(store=store.name)
    print (products)

Whether you need the id or the name of the store, you should be able to retrieve it with salesDude.store.id or salesDude.store.name.

Upvotes: 1

Related Questions