我的 models.py :
中有以下结构方案from django.db import models
class SensorManager(models.Manager):
def create_sensor(self,numero,pinoFisico):
sensor = self.create(numero = numero,
pinoFisico = pinoFisico,
ativo = False)
return sensor
class Sensor(models.Model):
numero = models.IntegerField()
pinoFisico = models.IntegerField()
ativo = models.BooleanField()
dataUltimoReconhecimento = models.DateTimeField()
situacao = None
moduloSensor = None
#Manager
objects = SensorManager()
def __init__(self):
self.moduloSensor = ModuloSensor()
并且,在 views.py 文件中,我有:
def formSensores(request):
sensores = Sensor.objects.all()
print sensores
return render(request,"speedapp/monitoraSensores.html",{"sensores": sensores})
当我尝试在
中使用对象时打印感官
我得到以下堆栈:
[17/Apr/2017 00:38:09] "GET /speedapp/ HTTP/1.1" 200 3649
Internal Server Error: /speedapp/sensores/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pi/Documents/speed_project/speed/speedapp/views.py", line 39, in formSensores
print sensores
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 234, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 258, in __iter__
self._fetch_all()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 69, in __iter__
obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end])
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 460, in from_db
new = cls(*values)
TypeError: __init__() takes exactly 1 argument (6 given)
[17/Apr/2017 00:38:11] "GET /speedapp/sensores/ HTTP/1.1" 500 15557
作为堆栈,在类Sensor
中的SensorManager
方法中__init__()
方法构建from_db
对象时,似乎是一个问题。预期 N 参数...此问题与我的自定义管理器SensorManager
有关?
P.S:
答案 0 :(得分:2)
所以这是高级答案。问题是您覆盖了模型上的__init__
方法。你真的应该尽量避免这种情况。这是关于其他选项的一些文档;阅读绿色大注:https://docs.djangoproject.com/en/1.11/ref/models/instances/#django.db.models.Model
以下是摘录:
You may be tempted to customize the model by overriding the __init__ method...Rather than overriding __init__, try using one of these approaches
1. Add a classmethod on the model class
2. Add a method on a custom manager (usually preferred)
如果你绝对需要覆盖__init__
,那么不要忘记调用super()
传递值,让Django先做它的东西。