需要什么查询集?
我有以下模型:
PHONE_CHOICES = (
('home', 'Home'),
('home2', 'Home 2'),
('mobi', 'Mobile'),
('mobi2', 'Mobile 2'),
('work', 'Work'),
('work2', 'Work 2'),
)
class ClientPhone(models.Model):
client = models.ForeignKey(Client, editable=False)
created = models.DateTimeField(default=datetime.now, editable=False)
created_by = models.ForeignKey(User,editable=False)
phone_type = models.CharField(max_length=5, choices=PHONE_CHOICES)
number = models.CharField(max_length=24)
我知道 ClientPhone.objects.filter(client=i_clientKEY).latest('created')
会给我输入数据库的最新电话号码,但我希望能够获取客户的“home”、“home2”、“mobi”等的最新电话号码...(全部)。
如何获取查询集来执行此操作?
I have the following model:
PHONE_CHOICES = (
('home', 'Home'),
('home2', 'Home 2'),
('mobi', 'Mobile'),
('mobi2', 'Mobile 2'),
('work', 'Work'),
('work2', 'Work 2'),
)
class ClientPhone(models.Model):
client = models.ForeignKey(Client, editable=False)
created = models.DateTimeField(default=datetime.now, editable=False)
created_by = models.ForeignKey(User,editable=False)
phone_type = models.CharField(max_length=5, choices=PHONE_CHOICES)
number = models.CharField(max_length=24)
I know ClientPhone.objects.filter(client=i_clientKEY).latest('created')
Will get me the latest phone number entered into the db, but I want to be able to get the latest phone numbers for 'home', 'home2', 'mobi', etc...(all) for a client.
How do I get a queryset to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
latest() 返回单个查询对象,而不是列表,因此您将获得最新的电话。相关人员的记录。
如果您希望获取每个phone_type的最新号码,则必须执行不同的sql查询,这意味着您必须为每个phone_type编写不同的查询...
@Aldarund:使用phone_type__in可以帮助您获取最新的 号码记录列表中某个元素的phone_type(具有最新创建时间的一个。),但不是列表中每个元素的一个结果
latest() returns a single query object, not a list, so you will get tha latest tel. record of related person.
If you wish to get the latest nmber for each phone_type, you must execute diffrent sql queries, so that means you must write diffrent queries for each phone_type...
@Aldarund: using phone_type__in helps you to get latest record with phone_type of one of the elements of the list(one with the latest creation time.), but not one result for each element in the list
只需添加另一个参数来过滤,如下所示:
ClientPhone.objects.filter(client=i_clientKEY,phone_type='home').latest('创建')
Just add another argument to filter like this:
ClientPhone.objects.filter(client=i_clientKEY,phone_type='home').latest('created')