简体   繁体   中英

Django: how can i show the data of two or three models

hi working on a project where data is inherited from multiple models. I don't know how to show the data of multiple models of a particular user.this is my first model user 1.

class Loader_post(models.Model):
     user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Loader", null=True)
     pick_up_station = models.CharField(max_length=150)
     destination_station = models.CharField(max_length=150)
     sender_name = models.CharField(max_length=150)
     phone_number = PhoneNumberField(null=False, blank=False, default='')

this is the second model where user2 add price on above post

class price(models.Model):
    my_post = models.ForeignKey(Loader_post, related_name='prices', on_delete=models.CASCADE, 
    null=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='')
    driver_price = models.CharField(max_length=150, null=True)
    status = models.BooleanField(default=False)

this is third model of user2 of booking

class Booking(models.Model):
    post = models.ForeignKey(price, related_name='b_post', on_delete=models.CASCADE, 
    default='', null=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='')
    approved_price = models.BooleanField(default=False)

Make sure you passed it in the views.py and imported it from.models. Should look something like this:

from django.shortcuts import render
from .models import model1

def index(request):

   model1 = model1.objects.all()

   context = {'model1': model1}

   render (request, '<template_name>', context)

And for the HTML part if you are sorting through a query it would look like this:

{% for object in model1 %}
{{ object }} # if you want a certain field it should be {{ object.<field_name> }} where <field_name> is the name of your field
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM