Django过滤对象并获得第一个相应的值

时间:2016-08-15 10:17:26

标签: python django

我有两个模特。

class House(models.Model):
    name= models.Charfield(max_length=100)
    city= models.Charfield(max_length=100)
    area= models.CharField(max_length=200)
    country=models.CharField(max_length=30)

class HouseRooms(models.Model):
    room_name=models.Charfield(max_length=200)
    house= models.ForeignKey(House, related_name='house_hr')
    room_price=models.PositiveIntegerField()

当用户运行关键字搜索时,我想返回每个' House'以及相应的HouseRooms'的第一个room_price。请参阅下面的观点。

def my_house_search(request):
    query_string= ''
    rms= None
    sms=None
    if ('q' in request.GET) and request.GET['q'].strip():
        query_string = request.GET['q']

        entry_query= get_query(query_string, ['city','country',])

        rms= House.objects.filter(entry_query).order_by('-pub_date')
        sms= HouseRooms.objects.filter(house_id__in=rms)


        return render(request, 'search/my_house_search.html',{'rms':rms, 'sms':sms, 'query_string':query_string})

模板:

 {% if query_string %}
     <p> Results </p>


     {% if rms %}
      {% for m in rms %}
         <p> Name: {{ m.name }} </p>
      {% empty %}
          <p> No house found </p>
      {% endfor %}

      {% for sd in sms %}
        <p> price: {{ sd.room_price }} for {{sd.room_name}}</p>
      {% empty %}
         <p> no price found </p>
      {% endfor %}

    {% endif %}

    {% endif %}

根据我写的代码,它将返回每个房子的名称,并显示所有房屋的所有价格,如下所示:

Coker House

Klopp House

$50/day for small room
$100/day for medium room
$200/day for big room

$200/day for quack room
$400/day for master room
$500/day for big room

我只是想让它像这样返回结果。

Coker House
$50/day for small room

Klopp House
$200/day for quack room

我错过了什么?我该怎么做?

1 个答案:

答案 0 :(得分:2)

您不应在视图中明确查询HouseRooms。相反,您可以在模板本身的迭代中使用反向关系访问器。

{% for m in rms %}
  <p> Name: {{ m.name }} </p>
  {% with m.house_hr.first as sd %}
    {% if sd %}
      <p> price: {{ sd.room_price }} for {{sd.room_name}}</p>
    {% else %}
      <p> no price found </p>
    {% endif %}
  {% endwith %}
{% empty %}
  <p> No house found </p>
{% endfor %}