[英]Making a simple query with Django Models
I want to get only one value (for example, one "cantidad", BUT ONLY ONE , even if there are repeated values). 我只想获得一个值(例如,即使有重复的值,也可以是一个“ cantidad”, 但只能是一个 )。
This is my model: 这是我的模型:
from django.db import models
from django.utils import timezone
class Data(models.Model):
palabra = models.CharField(max_length=200)
cantidad = models.IntegerField()
fecha = models.DateTimeField(
default=timezone.now)
def returnFecha(self):
return self.fecha
def __str__(self):
return self.palabra , self.cantidad , self.fecha
Taking into account that I have already filled the table/db with data, I have tried this: 考虑到我已经用数据填充了表/数据库,我尝试了以下方法:
q1=Data.objects.get(cantidad=56).first()
But this gets me this error: 但这让我遇到这个错误:
get() returned more than one Data -- it returned 7!
Why? 为什么? Having first()
should not cause any problems. 拥有first()
不会造成任何问题。
Returns the object matching the given lookup parameters , which should be in the format described in Field lookups. 返回与给定查找参数匹配的对象 ,该参数应采用“字段查找”中所述的格式。
get() raises MultipleObjectsReturned if more than one object was found. 如果找到多个对象,则get()会引发MultipleObjectsReturned。 The MultipleObjectsReturned exception is an attribute of the model class. MultipleObjectsReturned异常是模型类的属性。
get
returns a single object, not query-set
. get
返回单个对象,而不是query-set
。 That's why we can't use first()
after get
. 这就是为什么我们不能在get
之后使用first()
。
Returns a new QuerySet containing objects that match the given lookup parameters. 返回一个新的QuerySet,其中包含与给定查找参数匹配的对象。
filter
returns query-set
. filter
返回query-set
。 You can use first()
after filter
您可以在filter
之后使用first()
You need to use filter
and then first()
, 您需要使用filter
,然后使用first()
,
Data.objects.filter(cantidad=56).first()
You have to write: 您必须写:
q1 = Data.objects.filter(cantidad=56).first()
It returns the first object from your list object with cantidad=56
. 它从清单对象中返回第一个对象,其cantidad=56
对象为cantidad=56
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.