Table level logic Django - python

I have this model:
class Sesion(models.Model):
maq = models.CharField(max_length=25)
ini_sesion = models.DateTimeField(auto_now_add=True)
fin_sesion = models.DateTimeField(null=True, blank=True)
cont_ini_a = models.IntegerField(null=True, blank=True)
con_ini_b = models.IntegerField(null=True, blank=True)
con_fin_a = models.IntegerField(null=True, blank=True)
con_fin_b = models.IntegerField(null=True, blank=True)
#staticmethod
def cierre():
instance = Sesion.objects.filter(fin_sesion__isnull=True).latest('ini_sesion')
sesion_abierta = None
try:
sesion_abierta = Sesion.objects.filter(maq=instance.maq).filter(fin_sesion__isnull=True) \
.filter(ini_sesion__lt=instance.ini_sesion).latest('ini_sesion')
except Exception:
print('Ha ocurrido una excepcion!')
if sesion_abierta:
sesion_abierta.con_fin_a = instance.con_fin_a
sesion_abierta.con_fin_b = instance.con_fin_b
sesion_abierta.fin_sesion = instance.ini_sesion
return sesion_abierta.save()
Now the thing is i can't make it work every time a model instance is saved. I works when it is called from python/django shell
>>> Sesion.cierre()
but not when a model instance is saved and it doesn't work on save() override or signals either. Thx in advance.

Well I will answer the question. Here is what worked:
#receiver(post_save, sender=Sesion)
def cierre(*args, **kwargs):
instance = Sesion.objects.filter(fin_sesion__isnull=True).latest('ini_sesion')
sesion_abierta = None
try:
sesion_abierta = Sesion.objects.filter(maq=instance.maq).filter(fin_sesion__isnull=True) \
.filter(ini_sesion__lt=instance.ini_sesion).latest('ini_sesion')
except Exception:
print('Ha ocurrido una excepcion!')
if sesion_abierta:
sesion_abierta.con_fin_a = instance.con_fin_a
sesion_abierta.con_fin_b = instance.con_fin_b
sesion_abierta.fin_sesion = instance.ini_sesion
sesión_abierta.save()
Edit: Note that the "signals" code goes on the same line of indentation as
class Sesion(models.Model):

Related

Manager object has no attribute 'save'

In my serializers.py I have a OrderCreateSerializer:
class OrderCreateSerializer(ModelSerializer):
data_params = serializers.DictField() # 根据产品数据模型不同而异
class Meta:
model = Order
fields = (
"product_describe", # 产品描述 (购买xx产品 + 参数)
"billing_type", # 计费类型 ("包年包月")
"data_params", # 数据
)
def create(self, validated_data):
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
validated_data["order_num"] = generateOrderNum(userid=user.id)
validated_data["order_status"] = "未支付"
validated_data["order_status"] = "未支付"
data_dic = validated_data.pop("data_params") #
# data_dic["data"]["profile"]
validated_data["buytime"] = data_dic["data"]["buytime"]
validated_data["count"] = data_dic["data"]["count"]
validated_data["paytype"] = ""
validated_data["cost"] = ""
validated_data["account"] = user.account
return Order.objects.save(**validated_data) # this is the line 57
When I save the validated_data, it report the bellow error:
Manager object has no attribute 'save'
My Order model is like bellow, there is many fields in it :
class Order(models.Model):
"""
订单
"""
order_num = models.CharField(max_length=128, unique=True) # 订单编号
order_status = models.CharField(max_length=12) # 订单状态 "未支付", "已支付,未完成", "已完成", "已经删除","其他"
product_describe = models.TextField() # 产品描述
billing_type = models.CharField(max_length=16) # 计费类型
buytime = models.CharField(max_length=16) # 比如:1月 永久
count = models.IntegerField() # 购买数量
paytype = models.CharField(max_length=16) # 支付方式(支付包,微信,xxx)
cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00) # 费用(需要花费多少钱)
account = models.ForeignKey(to=Account) # 所属账户
ctime = models.DateTimeField(auto_now_add=True) # 创建时间
uptime = models.DateTimeField(auto_now=True) # 更新时间
def __str__(self):
return self.product_describe
def __unicode__(self):
return self.product_describe
I don't know why there is the Manager object here.
You're calling save on the manager (ie, objects)
return Order.objects.save(**validated_data)
You call save on models.
I assume you're trying to create the model, in which case you want create.
return Order.objects.create(**validated_data)
Order.objects is an instance of the Manager class. The save method is a method of the model class.
Try:Order(**validated_data).save()

Django rest framework - NOT NULL constraint on a foreign Key

I have this Error :
IntegrityError at /api/post_flight_schedule/
NOT NULL constraint failed: flights_tailnumber.aircraft_type_id
When I try to add a new PosFlightSchedule object to DB over http://127.0.0.1:8000/api/pos_flight_schedule (Website/APIView)
I have the below serializer :
class PosFlightScheduleModelSerializer(ModelSerializer):
class Meta:
model = PosFlightSchedule
fields = ['pos_route_id', 'tail_number', 'pos_flight_number', 'pos_flight_departure_time', 'pos_flight_date',
'pax_count']
class PosFlightScheduleSerializer(serializers.Serializer):
pos_route_id = serializers.CharField(source='pos_route_id.route_id', read_only=False)
tail_number = serializers.CharField(source='tail_number.tail_number', read_only=False)
pos_flight_number = serializers.CharField(source='pos_flight_number.flight_number', read_only=False)
pos_flight_departure_time = serializers.CharField(source='pos_flight_departure_time.flight_departure_time', allow_null=True,
read_only=False)
pos_flight_date = serializers.CharField(source='pos_flight_date.flight_date', read_only=False)
pax_count = serializers.IntegerField(read_only=False)
def create(self, validated_data):
tail_number_data = validated_data.pop("tail_number")
tail_number = TailNumber.objects.create(**tail_number_data)
flight_number_data = validated_data.pop("pos_flight_number")
flight_number = FlightSchedule.objects.create(**flight_number_data)
flight_departure_time_data = validated_data.pop("pos_flight_departure_time")
print "DEP_TIME" + str(flight_departure_time_data)
flight_departure_time = FlightSchedule.objects.create(**flight_departure_time_data)
route_id_data = validated_data.pop("pos_route_id")
route_id = FlightScheduleDetail.objects.create(**route_id_data)
flight_date_data = validated_data.pop("pos_flight_date")
flight_date = FlightScheduleDetail.objects.create(**flight_date_data)
pax_count = validated_data.pop("pax_count")
schedule_obj = PosFlightSchedule.objects.create(**validated_data)
# if tail_number:
schedule_obj.set_tail_number(tail_number)
schedule_obj.set_pos_flight_number(flight_number)
schedule_obj.set_pos_flight_departure_time(flight_departure_time)
schedule_obj.set_pos_route_id(route_id)
schedule_obj.set_pos_flight_date(flight_date)
schedule_obj.set_pax_count(pax_count)
schedule_obj.save()
return schedule_obj
def update(self, instance, validated_data):
tail_number = validated_data.pop("tail_number")
flight_number = validated_data.pop("pos_flight_number")
flight_departure_time = validated_data.pop("pos_flight_departure_time")
route_id = validated_data.pop("pos_route_id")
flight_date = validated_data.pop("pos_flight_date")
pax_count = validated_data.pop("pax_count")
instance.__dict__.update(validated_data)
if tail_number:
instance.set_tail_number(tail_number)
if flight_number:
instance.set_pos_flight_number(flight_number)
if flight_departure_time:
instance.set_pos_flight_departure_time(flight_departure_time)
if route_id:
instance.set_pos_route_id(route_id)
if flight_date:
instance.set_pos_flight_date(flight_date)
if pax_count:
instance.set_pax_count(pax_count)
instance.save()
return instance
The model of the field which is giving error looks like :
class TailNumber(models.Model):
tail_number_id = models.AutoField(null=False, primary_key=True)
tail_number = models.CharField(max_length=20, null=False, blank=False, unique=True)
aircraft_type = models.ForeignKey(AircraftType, null=False, blank=False)
def __unicode__(self):
return u'%s' % self.tail_number
class Meta:
verbose_name_plural = "Tail Numbers"
I am not understanding what is going wrong here.
The error you get is probably due to the fact that the dictionary tail_number_data does not contain the keyword aircraft_type, which is expected by TailNumber.objects to create the row in the db, since you defined it with no possibility to be null
aircraft_type = models.ForeignKey(AircraftType, null=False, blank=False)
^^^^^
Check that the key "aircraft_type" does exist in the dictionary tail_number_data, or allow for it to be null. Furthermore, if you consider the latter option and that this information is supposed to come from a UI, you may also want to allow for aircraft_type to be blank. See differentiate null=True, blank=True in django for details.

'QuerySet' object has no attribute ''cantidad_update"

how are you? I have this error when trying to subtract the values ​​in an IF where it is subtracted if the quantity_update is greater than 0. and if it does not subtract only the quantity.
models.py:
class Pedido(models.Model):
especialidad = models.ForeignKey('Especialidad')
articulo = models.ForeignKey('Articulo')
fecha_entrega = models.DateTimeField(auto_now_add=False, null=True, blank=True)
fecha_pedido = models.DateTimeField(auto_now_add=False,null=True, blank=True)
cantidad = models.IntegerField(blank=True, default=0)
estado = models.CharField(max_length=20, blank=True)
cantidad_update = models.IntegerField(blank=True, default=0)
estado_update = models.CharField(max_length=20, blank=True)
class Articulo(models.Model):
cod_experto = models.CharField(max_length=999, primary_key=True, blank=True)
nombre = models.CharField(max_length=999, blank=True)
on_delete=models.CASCADE)
stock = models.IntegerField(blank=True, default=0)
Views.py Query:
def Entregar(request, id_especialidad):
if request.method == 'GET':
especialidad = Especialidad.objects.get(id=id_especialidad)
pedido = Pedido.object.filter(especialidad=especialidad).filter(estado='pendiente')
if pedido.cantidad_update > 0: #Here is the error!
pedido.articulo.stock -= pedido.cantidad_update
else:
pedido.articulo.stock -= pedido.cantidad
pedido.save()
pedido2 = Pedido.objects.filter(especialidad=especialidad).filter(estado='pendiente').update(estado='entregado').update(fecha_entrega=datetime.date.today())
return HttpResponseRedirect('/solicitar/lista_super/%s/' % id_especialidad)
This would be relevant and I do not know that I'm missing, some help please!
Change
pedido = Pedido.object.filter(especialidad=especialidad).filter(estado='pendiente')
` to
pedido = Pedido.object.filter(especialidad=especialidad).filter(estado='pendiente')[0]
# or use for x in y to iterate each item`,
Your error occurs because filter() returns Queryset, not Pedido Object!
But in your case why are you using filter instead of get!
Using pedido = Pedido.object.filter(especialidad=especialidad).filter(estado='pendiente')[0] as long as there is data to retrieve. But when there is no data ? the query fails and the page returns 500 error. Because None queryset will not have 0th element.
Consider using get_object_or_404 since you want to get single object. Use something like which will be fail
def Entregar(request, id_especialidad):
if request.method == 'GET':
especialidad = get_object_or_404(Especialidad, id=id_especialidad)
pedido = get_object_or_404(Pedido, especialidad=especialidad, estado='pendiente')
if pedido.cantidad_update > 0: # Here is the error!
pedido.articulo.stock -= pedido.cantidad_update
else:
pedido.articulo.stock -= pedido.cantidad
pedido.save()
pedido2 = get_object_or_404(Pedido, especialidad=especialidad, estado='pendiente')
pedido2.update(estado='entregado').update(fecha_entrega=datetime.date.today())
return HttpResponseRedirect('/solicitar/lista_super/%s/' % id_especialidad)

Django won't syncdb after adding a method to a model

When I add the check_stats() method manage.py hangs. The within_range() and light_check() functions are imported from a custom library. I've tried running syncdb with verbosity, but I receive no errors. I'm unable to stop the process with ctrl+c and have to close the terminal window. After this I'm no longer able to run any commands from manage.py without getting the same problem. I had another function in another file that did the same exact thing, but I wanted to use a method instead. I've deleted the db and tried syncing again and no db even gets created unless I remove that method.
class PlotZone(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=40, blank=True)
plot_comments = models.CharField(max_length=500, blank=True)
current_temp = models.IntegerField(default=0)
current_humid = models.IntegerField(default=0)
light_start = models.TimeField(blank=True, null=True)
light_stop = models.TimeField(blank=True, null=True)
light_status = models.BooleanField(default=True)
goal_temp = models.IntegerField(default=0)
goal_humid = models.IntegerField(default=0)
humid_alert = models.NullBooleanField(default=False)
temp_alert = models.NullBooleanField(default=False)
light_alert = models.NullBooleanField(default=False)
alert_status = models.NullBooleanField(default=False)
humid_fail_limit = models.IntegerField(default=0)
temp_fail_limit = models.IntegerField(default=0)
def check_stats(self):
if not within_range(self.goal_temp, self.current_temp, self.temp_fail_limit):
self.alert_status = True
elif not within_range(self.goal_humid, self.current_humid, self.humid_fail_limit):
self.alert_status = True
elif not light_check(self, datetime.time()):
self.alert_status = True
def within_range(goal, current, fail_limit):
goal = int(goal*10)
current = int(current*10)
fail_limit = int(fail_limit*10)
lower_range = range((goal-fail_limit), goal+1)
upper_range = range(goal, (goal+(fail_limit+1)))
if (current in lower_range) or (current in upper_range):
return True
else:
return False

Did I set this up correctly?

I'm asking if I set up the create method up correctly. Or does it need to be added for the other two models as well? How would this be changed?
class PointModel(models.Model):
x = models.IntegerField()
y = models.IntegerField()
index = models.IntegerField()
class DatetimeRangeModel(models.Model):
start_datetime = models.CharField(max_length=14)
end_datetime = models.CharField(max_length=14)
class PlanModel(models.Model):
data_number = models.IntegerField()
data_datetime_range = models.ForeignKey(DatetimeRangeModel, blank=True, null=True, on_delete=models.SET_NULL)
data_polygon = models.ForeignKey(PointModel, blank=True, null=True, on_delete=models.SET_NULL)
#classmethod
def create(cls, data_number, data_datetime_range, data_polygon):
plan = cls(data_number=data_number, data_datetime_range = data_datetime_range,
data_polygon=data_polygon)
return plan
EDIT: I change the structure which fixed the undefined and added some logic that prevents the PlanModel from being deleted with the "blank=True, null=True, on_delete=models.SET_NULL"
Does this look right?
see the docs for creating objects
#classmethod
def create(cls, title):
book = cls(title=title)
# do something with the book
return book
there's no much reason to add those unless you have something to add there on the # do something with the book line
EDIT: instead of calling create you're usually do:
plan = PlanModel(data_number=1, ....)
plan.save()
or sometimes:
plan = PlanModel()
plan.data_number=1
...
plan.save()

Categories