Home > OS >  How to display database data to your website?
How to display database data to your website?

Time:12-02

This is a very simple question that got me stuck. I have 2 tables that are connected: Dealershiplistings, Dealerships. On my website I need to display the Model, Make and year of the car (Which are all stored in the DealershipListing, so i have no problem wiht this part) but I also need to print the address that is stored in the Dealerships table. Can anyone help me with this?

this is what i have for my views.py

def store(request):
    dealer_list = Dealer.objects.all()
    car_list = DealershipListing.objects.all()
    context = {'dealer_list': dealer_list, 'car_list': car_list}
    return render(request, 'store/store.html', context)

i tried doing

{{%for car in car_list%}}
<h6>{{car.year}} {{car.make}} {{car.model}}</h6>
{% endfor %}

which works perfectly displaying those. But now how do i display the address of the dealership that is selling the car?

models.py

class Dealer(models.Model):
    dealersName = models.TextField(('DealersName'))
    zipcode = models.CharField(("zipcodex"), max_length = 15)
    zipcode_2 = models.CharField(("zipCode"), max_length = 15)  
    state = models.CharField(("state"), max_length=5)
    address = models.TextField(("Address"))
    dealerId = models.IntegerField(("ids"), primary_key=True)
    

    def __str__(self):
        return self.dealersName


class DealershipListing(models.Model):
    carID = models.IntegerField(("CarID"), primary_key=True)
    price = models.IntegerField(('price'))
    msrp = models.IntegerField(('msrp'))
    mileage = models.IntegerField(('mileage'))
    is_new = models.BooleanField(('isNew'))
    model = models.CharField(("Models"), max_length= 255)
    make = models.CharField(("Make"), max_length=255)
    year = models.CharField(("Year"),max_length=4)
    dealerID = models.ForeignKey(Dealer, models.CASCADE)

    def __str__(self):
        return self.year   " "   self.make   " "   self.model

CodePudding user response:

So then it looks like your question is really How do I access data from a foreign key in a template?

The answer is refreshingly simple!

{{car.dealerID.address}}

On a side note, you might want to rename dealerID to dealer, django will handle the db column names how it sees fit, so while you might access the data with .dealer the db column would be named dealer_id by django automatically. Renaming the field also makes it more obvious that accessing it will give you a dealer and not its id.

CodePudding user response:

calling with the model name is what I prefer to use

{{obj.related_table.field_name}}

I think this pattern may help you solve problem related to getting related field value

  • Related