pythondjangopython-2.7django-1.5

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.


Solution

  • 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()