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")
现在
>>> 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'
我不明白为什么会这样。有人可以帮帮我吗?
编辑:
抱歉没有发送所有代码 - 问题已解决。 在我的另一个班级hardware_type = models.ManyToManyField(Hardware_type, verbose_name="Hardware Type")
从hardware_type更改为hw_type后,正常工作 我不知道会导致这个问题。
答案 0 :(得分:12)
如果您向模型添加自定义管理器,则不会创建objects
处的默认管理器。可以在类定义中自行添加,也可以使用自定义管理器。
答案 1 :(得分:1)
您的代码适合我:
>>> hw = Hardware_type.objects.get(slug='111')
>>> hw
<Hardware_type: Hardware_type object>
但是,使用关键字 type
可能有点危险,可能您希望避免使用它。
答案 2 :(得分:1)
后来我注意到我在forms.py
中有一些旧代码class Hardware_type(forms.ModelForm):
class Meta:
model = Hardware_type
因此它不起作用,这对于命名类等来说是糟糕的一天。
答案 3 :(得分:0)
就我而言,我模型的元类有import numpy as np
arr1 = np.genfromtxt('one.txt', delimiter=" ")
# arr = [[1.0, 2.0], [3.0, 4.0], [2.0, 3.0]]
arr2 = np.genfromtxt('two.txt', delimiter=" ")
# arr2 = [3.0, 1.0, 5.0, 1.0, 1.2, 1.4]
arr2 = np.reshape(arr2, (arr1.shape[1], arr1.shape[0]))
# arr2 = [[3.0, 1.0, 5.0], [1.0, 1.2, 1.4]]
arr2 = arr2.T
# arr2 = [[3.0, 1.0], [1.0, 1.2], [5.0, 1.4]]
out = arr1+arr2.reshape(arr1.shape)
print(out)
# out = [[4.0, 3.0], [4.0, 5.2], [7.0, 4.4]]
我正在使用model.objects.all()。
由于不能实例化抽象,因此我们不能使用它。