显示来自另一个Model Django的对象列表

时间:2018-02-17 14:52:24

标签: python django

我是stackoverflow的新手,我不知道如何正确粘贴Django代码。请耐心等待。

无论如何,这是我的问题: “我想在模板中显示DormRoom.room_number作为列表(示例:房间:401,402,403,404等)。”

enter image description here

Models.py>

class Dorm(models.Model):
   dorm_name = models.CharField(max_length=50, help_text="Enter dorm name")
   dorm_description = models.TextField(max_length=1000, help_text="Enter dorm description")
   dorm_primary_picture = models.ImageField(help_text="Enter dorm primary pic")
   dorm_room_count = models.IntegerField(help_text="Enter no. of rooms")
   dorm_address = models.CharField(max_length=100,help_text="Enter dorm address")
   dorm_caretaker = models.CharField(max_length=50,help_text="Enter caretaker name")
   dorm_contact_no = models.CharField(max_length=50,help_text="Enter dorm contact number")
   dorm_contact_email = models.EmailField(max_length=254,help_text="Enter dorm email")
   dorm_date_added = models.DateTimeField(help_text="Enter Date Dorm was created")
   dorm_availability = models.CharField(max_length=50, help_text="Is dorm available")
   dorm_date_updated = models.DateTimeField(help_text="Enter Date Dorm information was updated")
   dorm_house_rules = models.TextField(max_length=1000, help_text="Enter dorm house rules")

   class Meta:
      ordering = ["-dorm_name"]

   def get_absolute_url(self):
      return reverse('dorm-detail',args=[str(self.id)])

   def __str__(self):
      return self.dorm_name

class DormRoom(models.Model):
   room_number = models.CharField(max_length=20, help_text="Enter room number")
   room_maxusers = models.IntegerField(help_text="Enter maximum # of room users")
   room_dorm = models.ForeignKey(Dorm, on_delete=models.CASCADE)
   room_count = models.IntegerField(help_text="Enter # of rooms in this Dorm room")

   def get_absolute_url(self):
      return reverse('rooms-detail', args=[str(self.id)])

   def __str__(self):
      return self.room_number

   class Meta:
      ordering = ('room_number',)

URLs.py>

from django.urls import path
from . import views

urlpatterns = [
  path('', views.index, name='index'),
  path('list/', views.DormsListView.as_view(), name='dorms'),
  path('list/<int:pk>', views.DormsDetailView.as_view(), name='dorm-detail'),
  path('rooms/', views.DormsRoomView.as_view(), name='rooms'),
  path('rooms/<int:pk>', views.DormsRoomsDetailView.as_view(), name='rooms-detail'),
]

Views.py&gt;

from django.shortcuts import render
from .models import Dorm, DormRoom
from django.views import generic
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin

# Create your views here.
@login_required
def index(request):
   num_dorms = Dorm.objects.all().count()

   num_visits = request.session.get('num_visits',0)
   request.session['num_visits'] = num_visits+1

   return render(
      request,
      'index.html',
      context = {'num_dorms':num_dorms,'num_visits': num_visits},
   )

class DormsListView(LoginRequiredMixin, generic.ListView):
   model = Dorm
   paginate_by = 4

class DormsDetailView(LoginRequiredMixin, generic.DetailView):
   model = Dorm

class DormsRoomView(LoginRequiredMixin, generic.ListView):
   model = DormRoom

class DormsRoomsDetailView(LoginRequiredMixin, generic.DetailView):
   model = DormRoom

Dorm_Detail.html&gt;

{% extends "base_generic.html" %}

{% block content %}
<div class="padding-small"><img class="image-standard" src="{{ dorm.dorm_primary_picture.url }}"/></div>
<h1><b>{{ dorm.dorm_name }}</b></h1>   
<h5>Address: {{ dorm.dorm_address }}</h5>   
<h5>{{ dorm.dorm_description }}</h5>
<div><br/></div>
<div>Available Rooms: {{ dorm.dorm_room_count}}</div>
<div>Rooms: {{ dormroom.room_number }}</div>
<div><br/></div>
<h4><b>Contact Details</b></h4>
<div>Administrator: {{ dorm.dorm_caretaker }}</div>
<div>Phone Number: {{ dorm.dorm_contact_no }}</div>
<div>Email Address: {{ dorm.dorm_contact_email }}</div>
<div>Date Added: {{ dorm.dorm_date_added }}</div>
<div>Last Updated: {{ dorm.dorm_date_updated }}</div>

<div><br/></div>
<h4><b>House Rules</b></h4>
<div>{{dorm.dorm_house_rules}}</div>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

使用template context及其object the DetailView providesroom_numbers添加到related manager:使用逗号加入values_list()返回的字符串。

class DormsDetailView(LoginRequiredMixin, generic.DetailView):
   model = Dorm

   def get_context_data(self, *args, **kwargs):
       context = super().get_context_data(*args, **kwargs)
       context['room_numbers'] = ", ".join(self.object.dormroom_set.values_list('room_number', flat=True))
       return context

然后相应地调整模板:

    <div><br/></div>
    <div>Available Rooms: {{ dorm.dorm_room_count}}</div>
    <div>Rooms: {{ room_numbers }}</div>
    <div><br/></div>
    <h4><b>Contact Details</b></h4>