如何在django中检索模型中的特定属性

时间:2017-02-25 07:17:57

标签: django

我们需要在django中检索特定房屋名称的所有玩家的名字

models.py:

class player(models.Model):
    """
    Model representing a book genre (e.g. Science Fiction, Non Fiction).
    """
    name = models.CharField(max_length=100, help_text="Enter a players name")
    Id = models.CharField(primary_key=True,max_length=100, help_text="Enter a players Id")
    Num_matches = models.IntegerField()
    Num_baskets = models.IntegerField()
    house_name = models.ForeignKey('House_name',on_delete=models.SET_NULL, null=True)

views.py:

def shivalik(request):
    queryset = player.objects.all().filter(house_name='shivalik' )
    return render(request,'shivalik.html',{'queryset': queryset})

shivalik.html:

{% extends "basic.html" %}

{% block content %}
<h2><li>{{queryset.name}}</li></h2>
{% endblock %}

错误:

ValueError at /bb/shivalik/
invalid literal for int() with base 10: 'shivalik'
Request Method: GET
Request URL:    http://127.0.0.1:8000/bb/shivalik/
Django Version: 1.10.5
Exception Type: ValueError
Exception Value:    
invalid literal for int() with base 10: 'shivalik'

1 个答案:

答案 0 :(得分:0)

这是因为models.ForeignKey用于int,而不是string值。你应该返回player.objects.all().filter(house_name=<int>)

如果您需要house_name中的特定名称,则应执行此操作;您models.py

中的示例
class House_name(models.Model):
    name = models.CharField(max_length=200)
    ....

然后在您的查询集中;

player.objects.filter(house_name__name='shivalik')