django ManyToMany显示相关对象

时间:2018-07-02 22:22:26

标签: django many-to-many manytomanyfield

搜索到处都找不到,尽管感觉很简单。

所以基本上我在models.py中有两个班级


class Restaurant(models.Model):
    restaurant_title = models.CharField(max_length=30)
    location = CountryField(null=True, blank_label='(select country)')
    first_purchase_discount = models.BooleanField(default=False)
    updated = models.DateTimeField(auto_now=True)
    slug = models.SlugField(max_length=30, unique=True)

def save (self, *args, **kwargs):
    self.slug = slugify(self.restaurant_title)
    super(Restaurant, self).save(*args, **kwargs)

def __str__(self):
    return self.restaurant_title

class Pizza(models.Model):
    pizza_title = models.CharField(max_length=20)
    restaurants = models.ManyToManyField('Restaurant', blank=True) 
    slug = models.SlugField(max_length=20, unique=True)


def save (self, *args, **kwargs):
    self.slug = slugify(self.pizza_title)
    super(pizza, self).save(*args, **kwargs)

def __str__(self):
    return self.pizza_title

现在我做了什么,就是在我的admin.py中注册模型。 我在那里创建了一个餐厅,例如Toni餐厅和Restaurant Pappo餐厅。 另一方面,我创建了披萨:A,B,C和D。 通过ManyToMany关系,我连接了Pizza A,B and C to ToniB, C and D to Pappo

在我的views.py中,我创建了一个列表视图,该视图用作主页,以显示通过以下方式显示所有餐厅的位置:

restaurants = Restaurant.objects.all()

要列出比萨饼,我创建了一个DetailView。我已经在restaurant_list.html(用作主页)中创建了一个链接来访问披萨

{% for restaurant in restaurants %} 
    <h2><a href="{% url 'pizza_detail' restaurant.slug %}">{{ restaurant.restaurant_title }}</a></h2>
{% endfor%}

我得到了餐厅,每个餐厅都将我链接到与之相关的比萨饼,或者至少我希望这样。

这里清晰可见我的views.py

class RestaurantListView(ListView):

    model = Restaurant

def get_context_data(self, **kwargs):
    context = super(RestaurantListView, self).get_context_data(**kwargs)
    return context

def home(request):
    template = 'restaurant/restaurant_list.html'
    restaurants = Restaurant.objects.all()
    context = {
        'restaurants': restaurants
    }
    return render(request, template, context)



class PizzaDetailView(DetailView):

    model = Pizza

def get_context_data(self, **kwargs):
    context = super(ShopDetailView, self).get_context_data(**kwargs)
    return context

def pizza_detail(request, slug):
    template = 'restaurant/pizza_detail.html'
    pizzas = Pizza.objects.all()
    context = {
        'pizzas': pizzas,
    }
    return render(request, template, context)

由于比萨饼= Pizza.objects.all()我显然得到了所有比萨饼。但是当然,我只想要相关的内容,这意味着当我单击Toni时,我想在单击“它的”链接时看到Pizze A,B和C以及相关的Pizza for Pappo。

我是否必须更改pizzas = Pizza.objects.all()中的for looppizza_detail.html,现在看起来像这样?

        {% for pizza in pizzas %}
                        <h1>{{pizza.pizza_title}}</h1>                  
        {% endfor%}

希望你明白我的意思。

Ps:您还能告诉我如何在我点击链接的pizza_detail.html中显示餐厅名称。 非常感谢<3

编辑

home.urls.py

urlpatterns = [
    url('admin/', admin.site.urls),
    url(r'^users/', include('django.contrib.auth.urls')),
    url(r'^', include('restaurant.urls')),
]

restaurant.urls.py
urlpatterns = [
    path('', home, name='restaurant_list'),
    path('restaurant/<slug:slug>/', pizza_detail, name='pizza_detail')  
]

2 个答案:

答案 0 :(得分:0)

比萨饼和餐厅有很多关系。您可以使用prefetch_related()从“餐厅”模型中查找披萨,反之亦然

示例:pizzas = Pizza.objects.all()。prefetch_related('restaurants')

如果要在pizza_detail.html中显示餐厅名称。使用示例查询并像这样更改html。

{% for pizza in pizzas %}
           {% for restaurant in pizza.restaurants %}   
                 {{restaurant.restaurant_title}}
           {% endfor%}
{% endfor%}

答案 1 :(得分:0)

如果您想在与特定餐厅有关的比萨饼上单击,还应该使用Restaurant模型来过滤数据

所以在 views.py

def pizza_detail(request, slug):
    template = 'restaurant/pizza_detail.html'
    restaurant = Restaurant.objects.get(slug=slug)
    pizzas = Pizza.objects.filter(restaurants__in=[restaurant])
    context = {
        'pizzas': pizzas,
        'restaurant': restaurant
    }
    return render(request, template, context)

pizza_detail.html

<h1>Restaurant : {{ restaurant.restaurant_title }}</h1> 
{% for pizza in pizzas %}
    <h3>{{pizza.pizza_title}}</h3>                  
{% endfor%}

注意restaurants__in查找仅接受可迭代项,因此特定的Restaurant对象作为list传递。