Get_by_natural_key throwing AttributeError?

1k views Asked by At

I'm having trouble using Django's get_by_natural_key() method. (Django 1.6)

I have Items which use code numbers like this: ABC_1234.

Manager and Model:

class ItemManager(models.Manager):
    def get_by_natural_key(self, code_number_):
        return self.get(code_number=code_number_)

class Item(models.Model):
    code_number = models.CharField('Code Number',
        max_length = 10, unique = True)
    def __unicode__(self):
        return self.code_number
    def natural_key(self):
        return (self.code_number,)

In my tests, I have this query...

Item.objects.get_by_natural_key(code_number)

... which throws this error:

AttributeError: 'Manager' object has no attribute 'get_by_natural_key'

I'd like to use this code_number as a natural key for related model fixtures, as well as a general purpose means of querying this model.

What am I doing wrong? Any suggestions?

1

There are 1 answers

1
Daniel Roseman On BEST ANSWER

You haven't associated your custom manager with the model. You need to do so explicitly:

class Item(models.Model):
    ...
    objects = ItemManager()