0

ユーザーが特定の製品名をクリックすると、関連するレビューを返そうとしています。私が使用しているビューは次のとおりです。

def index(request):
    prod_list = Website.objects.values('productname').distinct()
    return render_to_response('reserve/templates/index.html', {'prod_list': prod_list})

私が持っているテンプレートは次のとおりです。

 {% for website in prod_list %}
        <a href="/clubs/{{ website.id }}/detail">{{ website.productname }}</a>
        <br>{{  website.review }} <br><br>
    {% endfor %}

私が使用しているモデルは次のとおりです。

class Website(models.Model):
    productname = models.CharField('Website name', max_length = 100)
    review = models.CharField('Review', max_length = 200)
    def __unicode__(self):
        return self.productname

リストされている各製品名には複数のレビューがあります。私が直面している問題は、リンク ( ) が website.id を返さないことです。これを修正する方法について何かアドバイスはありますか?

4

2 に答える 2

1

モデル構造は実際には適切ではありません。本当に必要なのは、レビューと製品の別々のテーブル、次にForeignKeyレビューから製品へのテーブルで、1対多の関係になります。次に、それぞれの個別の製品を簡単に入手し、それぞれのレビューを繰り返すことができます。

于 2012-06-20T08:18:10.513 に答える
1

ドキュメントから

値(*フィールド)

ValuesQuerySet を返します — モデル インスタンス オブジェクトではなく反復可能オブジェクトとして使用された場合に辞書を返す QuerySet サブクラス。

したがって、実際に反復しているのは辞書オブジェクトです。

次に、値フィールドを制限すると、それらのフィールドのみが返されます。prod_list実際には:

[{'productname': u'Product Name 1'},{'productname': u'Product Name 2'}, ...]

ビューをこれに更新するprod_list = Website.objects.distinct('productname')と、クエリセットが返されるため、テンプレートが正しくレンダリングされます。

編集

は postgresql でのみサポートされているためDISTINCT ON、次の回避策を使用できます。

from django.shortcuts import render
# ... your other imports

def index(request):

    prod_list_distinct = set()
    for obj in Website.objects.all():
       prod_list_distinct.add(obj.productname) # sets only allow uniques

    prod_list = Website.objects.filter(productname__in=prod_list_distinct)

    return render(request,
                  'reserve/templates/index.html', {'prod_list': prod_list})
于 2012-06-20T04:59:16.877 に答える