Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: type object ... has no attribute 'objects'

fragment of models.py

class Hardware_type(models.Model):
    type = models.CharField(blank = False, max_length = 50, verbose_name="Type")
    description = models.TextField(blank = True, verbose_name="Description")
    slug = models.SlugField(unique = True, max_length = 255, verbose_name = "Slug")

class Software_type(models.Model):
    type = models.CharField(blank = False, max_length = 50, verbose_name="Type")
    description = models.TextField(blank = True, verbose_name="Description")
    slug = models.SlugField(unique = True, max_length = 255, verbose_name = "Slug")

and now

>>> sw = Software_type.objects.get(slug='unix')
>>> sw
<Software_type: Unix>
>>> hw = Hardware_type.objects.get(slug='printer')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: type object 'Hardware_type' has no attribute 'objects'

I can't see why this happens. Anyone can help me?

Edit:

sorry that did not sent all the code - problem solved. in another class I had

hardware_type = models.ManyToManyField(Hardware_type, verbose_name="Hardware Type")

after change from hardware_type to hw_type - works fine I did not know that can cause this problem.

like image 461
Kubas Avatar asked Oct 16 '11 16:10

Kubas


3 Answers

If you add a custom manager to a model then the default manager at objects will not be created. Either add it yourself in the class definition, or stick with using the custom manager.

like image 194
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 07:09

Ignacio Vazquez-Abrams


Your code works for me:

>>> hw = Hardware_type.objects.get(slug='111')
>>> hw
<Hardware_type: Hardware_type object>

However, using the keyword type might be a little dangerous, and probably you would like to avoid using it.

like image 26
Udi Avatar answered Sep 22 '22 07:09

Udi


it turned out that only began to work in django console,

Later I noticed that I have some old code in forms.py

class Hardware_type(forms.ModelForm):
    class Meta:
        model = Hardware_type

and thus it did not work, it was a bad day for naming classes, etc.

like image 24
Kubas Avatar answered Sep 19 '22 07:09

Kubas