代码之家  ›  专栏  ›  技术社区  ›  Davtho1983

在Django中查看ForiegnKey数据

  •  0
  • Davtho1983  · 技术社区  · 8 年前

    我想创建一个视图,显示Django中foreignkey的数据。

    我有一些理发师在特定日期有空,我想看看理发师在哪个日期有空。稍后,我需要知道哪些理发师在哪些日期有空。

    型号。py公司

    from django.db import models
    from datetime import time
    
    class Barber(models.Model):
    
        BARBERS = (
            ('KK', 'Kim Kardashian'),
            ('CJ', 'Caitlin Jenner'),
            ('KW', 'Kanye West')
        )
    
        LOCATION = (
            ('CL', 'Central Detroit'),
            ('NL', 'North Detroit'),
            ('SL', 'South Detroit'),
            ('EL', 'East Detroit'),
            ('WL', 'West Detroit'),
        )
    
        name = models.CharField(max_length=2, choices=BARBERS)
        location = models.CharField(max_length=2, choices=LOCATION)
    
        def __str__(self):
            return self.name
    
    class Date(models.Model):
    
        date = models.DateField()
        name = models.ForeignKey(Barber, on_delete=models.CASCADE)
    

    URL。我的应用程序中的py

    from django.urls import path
    from .views import schedule, appointments
    
    urlpatterns = [
        path('', schedule, name='schedule'),
        path('/appointments/<int:id>/', appointments, name='appointments')
    

    视图。py公司

    from django.shortcuts import render, redirect
    from .models import Barber, Date
    
    def schedule(request):
        barber = Barber.objects.all()
        return render(request, 'schedule.html', {'barber': barber})
    
    def appointments(request, name):
        dates = Date.objects.filter(name=name)
        return render(request, 'appointments.html', {'date': dates})
    

    约会。html

    <h1>Appointments</h1>
    
    <ul>
      {% for date in dates %}
        <li> {{ date.name }} {{ date.dates }} </li>
      {% endfor %}
    </ul>
    

    日程html:

    <h1>Schedule</h1>
    
    <ul>
      {% for barb in barber %}
        <a href="{% url 'appointments' Barber.id %}">
        <li> {{ barb.name }} {{ barb.location }} </li>
      {% endfor %}
    </ul>
    

    我得到的错误是:

    Reverse for 'appointments' with arguments '('',)' not found. 1 pattern(s) tried: ['\\/appointments\\/(?P<id>[0-9]+)\\/$']
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Lemayzeur    8 年前

    也许您的代码应该是:

    {% for barb in barber %}
        <a href="{% url 'appointments' bard.id %}">
        <li> {{ barb.name }} {{ barb.location }} </li>
    {% endfor %}
    

    视图

    def appointments(request, id):
        barb = Barber.objects.get(id=id)
        dates = barb.date_set.all()
        return render(request, 'appointments.html', {'dates': dates})