【问题标题】:django ManyToMany show related objectsdjango ManyToMany 显示相关对象
【发布时间】:2018-07-02 22:22:26
【问题描述】:

到处搜索,但即使感觉很简单,也找不到任何东西。

所以基本上我的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 和餐厅 Pappo。 另一方面,我创建了比萨饼:A、B、C 和 D。 通过多对多关系,我连接了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)

由于 Pizzas = Pizza.objects.all() 我显然得到了所有的 Pizzas。但当然我只想要相关的,这意味着当我点击 Toni 时,我想在点击“it's”链接时看到 Pizze A、B 和 C 以及相关的 Pappo 披萨。

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

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

希望你明白我的意思。

Ps:你能告诉我如何在我点击链接的pizza_detail.html 中也显示餐厅的名称吗? 非常感谢

编辑

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')  
]

【问题讨论】:

  • 为什么你有两种观点:一种是基于类的,另一种是基于功能的?这令人困惑......我认为你的缩进也很混乱。请解决这个问题。如果可能的话,我还想看看你的 urls.py 文件
  • 嗨,Alex,这只是一个 view.py,只是想强调一下我所做的。
  • 我的意思是你有RestaurantListView 然后def home(request): 做同样的事情。比萨饼也一样
  • 好吧,我明白了。因为我是初学者,所以我必须学习更多,但我只是添加了我的网址。希望你能帮我解决我的问题

标签: django many-to-many manytomanyfield


【解决方案1】:

如果您希望在点击时与特定餐厅相关的比萨饼,您还应该使用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 传递。

【讨论】:

  • Bijoy 非常感谢,工作完美。太奇怪了,这么简单的事情没有很好的记录
【解决方案2】:

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

示例: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%}

【讨论】:

  • 不知道为什么但是没有用,谢谢你的努力
猜你喜欢
  • 1970-01-01
  • 2010-12-18
  • 2020-08-24
  • 2015-06-01
  • 2021-04-16
  • 2020-09-03
  • 2023-03-03
  • 2013-10-20
  • 1970-01-01
相关资源
最近更新 更多