Django QuerySet with Models

Question:

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.

Asked By: Andrew

||

Answers:

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()
Answered By: ndpu

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')
Answered By: Daniel Roseman

I needed to access the queryset/manager for a different reason, since google brought me here – this ended up my solution:

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

    def get_channel_list(cls, acc):
        return self.__class__.objects.filter(accountid=acc).values_list('name', flat=True)
Answered By: S.D.