Django的多对多显示相关对象(django ManyToMany show related ob

2019-10-30 02:27发布

到处搜寻,但没有找到任何东西,即使它感觉如此简单。

所以基本上我有两个班在我的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 。 在那里,我创造了让我们说餐厅托尼和餐厅帕波。 在另一方面我创建的比萨饼: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)

由于比萨= Pizza.objects.all()我明明得到所有的比萨饼。 但是,当然,我只希望中关联的,这意味着当我对托尼点击,我希望看到Pizze A,B和C以及相关比萨饼的帕波当我点击“是”链接。

我一定要改变pizzas = Pizza.objects.all()for loop在我pizza_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')  
]

Answer 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查询只需要iterables,因此特别是Restaurant作为传递的对象list



Answer 2:

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

例如:。比萨饼= Pizza.objects.all()prefetch_related( '餐馆')

如果你想显示餐厅在pizza_detail.html名。 使用例如查询和修改HTML这样。

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


文章来源: django ManyToMany show related objects