简体   繁体   English

带有模型的Django QuerySet

[英]Django QuerySet with Models

I'm new to Django and trying to understand how to use querysets with models. 我是Django的新手,试图了解如何在模型中使用查询集。

Model
class Channel(models.Model):
    name = models.CharField(max_length=200)
    accountid = models.CharField(max_length=34)

    def get_channel_list(self):
        return self.get_queryset().name()

What I want to do is return the entire name column as an array if account id matches. 我想做的是,如果帐户ID匹配,则将整个名称列作为数组返回。 I'd like to use a function in the models.py but I haven't found an online sample that caters to what I'm looking for. 我想在models.py中使用一个函数,但是我没有找到能够满足我所寻找内容的在线示例。

The above isn't returning any data even without a filter. 即使没有过滤器,以上代码也不会返回任何数据。

Any point in the right direction would be amazing. 在正确方向上的任何一点都将是惊人的。

Use objects.filter and classmethod : 使用objects.filterclassmethod

class Channel(models.Model):
    name = models.CharField(max_length=200)
    accountid = models.CharField(max_length=34)

    @classmethod
    def get_channel_list(cls, acc):
        return cls.objects.filter(accountid=acc).values_list('name', flat=True)

There is another technique to do such things in django - define custom manager to model. 在django中还有另一种做这种事情的技术-定义要建模的自定义管理器。 (for example, you have several Channel models inherited from one base proxy model and you want to put same get_channel_list functions to some models - custom Manager is the way to go): (例如,您有从一个基本代理模型继承的多个Channel模型,并且您希望将相同的get_channel_list函数放置到某些模型中-定制管理器是一种解决方法):

class ChannelManager(models.Manager):
    def get_channel_list(self, acc):
        return self.filter(accountid=acc).values_list('name', flat=True)

class Channel(models.Model):
    name = models.CharField(max_length=200)
    accountid = models.CharField(max_length=34)

    objects = ChannelManager()

You have failed to understand the difference between managers and models. 您无法理解管理器和模型之间的区别。 It's the manager that it's responsible for creating queries, and which has the get_queryset method. 由经理负责创建查询,并具有get_queryset方法。 From a model, you need to access the manager, which is usually named objects. 从模型中,您需要访问管理器,通常称为对象。 Note, you cannot do that from an instance, so this needs to be a classmethod. 请注意,您不能从实例上执行此操作,因此这必须是一种类方法。

@classmethod
def get_channel_list(cls, accountid):
    return cls.objects.filter(accountid=accountid).values_list('name')

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

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