简体   繁体   English

在QuerySet.values()或values_list()中返回方法的结果?

[英]Return the result of a method in a QuerySet.values() or values_list()?

When calling .values() or .values_list() on a QuerySet you can pass in the specific fields you want returned, or even fields you want from related tables. 在QuerySet上调用.values()或.values_list()时,您可以传入要返回的特定字段,甚至从相关表中传入所需的字段。 What I'm wanting to do is include the result of a method defined on the model, in addition to some fields, for example: 除了一些字段,我想做的是包括模型上定义的方法的结果,例如:

class MyModel(models.Model):

    name = models.CharField()

    def favouriteNumber(self):
        return random.randint(1,10)

list(MyModel.objects.all().values('name','favouriteNumber'))
=> [{'name':'Bob', 'favouriteNumber':6}, {'name':'Fred', 'favouriteNumber':4}]

The above doesn't work, but is what I'm wanting to do, in the same way that the templating language can treat model methods without parameters just like fields. 上面的方法不起作用,但是这是我想要做的,就像模板语言可以像字段一样对待没有参数的模型方法一样。

The reason I'm wanting to do this is so that I can pass the information to the JavaScript in the front end to use instead of making calls back to the server to retrieve it each time. 我想要这样做的原因是,我可以将信息传递给前端的JavaScript以供使用,而不必每次都调用服务器来检索它。

Assuming the above (or something similar) isn't possible, I know I could loop over my values() result afterwards and add in the extra information manually.. what would be the most efficient (and clean) way to do that? 假设以上(或类似内容)是不可能的,我知道我可以在之后遍历我的values()结果并手动添加额外的信息。什么是最有效(最简洁)的方法?

You might want to try using only() instead of values() . 您可能想尝试使用only()而不是values() Like values() it will only fetch the specified fields from the database, but unlike values() it will return actual instance objects that you can call methods on. values()一样,它只会从数据库中获取指定的字段,但是与values()不同的是,它将返回可以调用方法的实际实例对象。

That way, whether you're looping in the view or the template, you can access the method in addition to the specified fields. 这样,无论您是在视图中还是在模板中循环,都可以访问指定方法之外的方法。

If you need dictionary-like structures (for json.dumps() , say) you can just construct them in a comprehension: 如果您需要类似字典的结构(例如json.dumps() ,则可以以一种理解的方式构造它们:

instances = MyModel.objects.only('name')
data = [{'name': instance.name, 
         'favourite': instance.favouriteNumber()} for instance in instances]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM