【问题标题】:A foreign key in the view details查看详细信息中的外键
【发布时间】:2015-05-09 18:47:42
【问题描述】:

我有一个 django 应用程序,您想在其中显示跟踪到特定画廊的所有图像,但我收到错误:“GalleryDetailsView1”对象没有属性“画廊”

型号

class Gallery(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    image = ThumbnailerImageField(upload_to='paint/%Y/%m/%d')

    class Meta:
        verbose_name = "Gallery"
        verbose_name_plural = " Galleries"

    def __unicode__(self):
        return self.title


class Paint(models.Model):
    AVAILABLE = "Available"
    NOT_AVAILABLE = "Not available"
    STATUS_PAINT = (
        (AVAILABLE, u"Dostępny"),
        (NOT_AVAILABLE, u"Nie dostępny")
    )
    title = models.CharField(max_length=200)
    gallery = models.ForeignKey(Gallery, related_name='paint_set')
    paint = ThumbnailerImageField(upload_to='paint/%Y/%m/%d')
    price = models.CharField(max_length=50, blank=True, null=True)
    status = models.CharField(choices=STATUS_PAINT, default=AVAILABLE, max_length=50)

观看次数

class GalleryList(generic.ListView):
    model = Gallery
    context_object_name = "list"
    template_name = "www/gallery_list.html"


class GalleryDetailsView1(generic.DetailView):
    context_object_name = "images1"
    template_name = "www/gallery_details1.html"

    def get_queryset(self):
        return Gallery.objects.get(pk=self.kwargs['pk']).paint_set.all()

模板:gallery_details1

{% extends "base.html" %}
{% load thumbnail %}

{% block content %}


{% for i in images1 %}

{{ i.title }}
<hr>
{% endfor %}


{% endblock %}

{% block content_bottom %}{% endblock content_bottom %}

【问题讨论】:

    标签: python django templates views django-queryset


    【解决方案1】:

    当您提出请求时,您必须以某种方式通过画廊pk。例如,作为您 URL 的一部分,然后从视图中的self.kwargs['gallery_pk']gallery_pk 位将取决于您的实现)中获取它:

    url(r'^api/gallery/(?P<gallery_pk>\d+)/paintset$', GalleryDetailsView1.as_view())
    

    然后你可以返回

    self.get_object().paint_set.all()
    

    作为您的查询集。

    最后但并非最不重要的一点是,画廊字段定义中的 related_name 参数应该是 "paint_set" 才能工作。

    【讨论】:

    • 对不起,我不得不问这个问题,但您是使用旧网址还是新网址进行测试?另外,你确定有主键的对象存在吗?
    • 这是我的网址:url(r'^gallery1/(?P&lt;pk&gt;\d+)/$', GalleryDetailsView1.as_view(), name="gallery_details1"),
    • 你测试的时候加了斜杠吗?
    • 我的输出:` 找不到页面 (404) 请求方法:GET 请求 URL:127.0.0.1:8000/gallery1/3 引发者:www.views.GalleryDetailsView1 找不到与查询匹配的图片 `
    • Picture 在您的应用中代表什么?
    猜你喜欢
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 2014-10-08
    • 2020-10-15
    • 1970-01-01
    相关资源
    最近更新 更多