简体   繁体   中英

Django QuerySet with Models

I'm new to Django and trying to understand how to use querysets with models.

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. 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.

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 :

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. (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):

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. 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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