I have a model like below:
class PedidoComissao(models.Model):
artista = models.ForeignKey(Cliente, verbose_name='Artista')
pedido = models.ForeignKey(Pedido)
pedidoitem = models.ForeignKey(PedidoItem, verbose_name='Arte')
valor_receber = models.DecimalField(max_digits=11, decimal_places=2)
data_pagamento = models.DateTimeField(auto_now_add=False)
status = models.BooleanField(default=False)
origem_venda = models.CharField(null=True, blank=True, max_length=30)
class Meta:
verbose_name, verbose_name_plural = u'Comissão', u'Comissões'
When I try to insert data with a code like below:
comissao = PedidoComissao(artista = produto.artista_id,
pedido = pedido,
pedidoitem = item,
valor_receber = valor_receber,
origem_venda = origem_venda)
comissao.save()
I get an error like this:
Cannot assign "5809L": "PedidoComissao.artista" must be a "Cliente" instance.
What am I supposed to do?
artista = produto.artista_id
should probably be
artista = Cliente.objects.get(produto.artista_id)
but its hard to tell exactly,since we dont know what produto is
the problem is your model expects an actual Cliente instance not just its id ...
You are doing PedidoComissao(artista=produto.artista_id, ...), but artista should be an instance of the model class, not the id. You can either do PedidoComissao(artista_id=produto.artista_id, ...) or PedidoComissao(artista=produto.artista, ...)
Related
My TimeReport model looks like this:
class TimeReport(models.Model):
minutes_spent = models.PositiveIntegerField()
task = models.ForeignKey(Task, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
reported_for = models.DateField()
note = models.TextField(null = True, blank=True)
status = models.CharField(max_length=50, choices=State.choices, default=State.new)
user = models.ForeignKey(User, on_delete=models.PROTECT)
And my model serializer:
class TimeReportCreateSerializer(serializers.ModelSerializer):
class Meta:
model = TimeReport
fields = (
'id',
'minutes_spent',
'reported_for',
'note',
'status',
'task_custom_id',
)
task_custom_id = serializers.CharField()
def create(self, validated_data):
user = User.objects.get(auth_user_id = self.context['user_id'])
task = Task.objects.filter(custom_id = validated_data['task_custom_id']).filter(user = user.id).first()
report = TimeReport(**validated_data)
report.user = user
report.task = task
report.save()
return report
So, the problem is, that I want to take a custom value in a serializer, which is not a part of a model and do some custom logic with it - in this case search for the right 'task' in the database. But when I try to parse the model by using report = TimeReport(**validated_data), it gives me an exception:
TypeError at /api/report/
TimeReport() got an unexpected keyword argument 'task_custom_id'
Im kind of new to Django and python itself, so - what is the best approach?
If you are going to use that field only for creation, you should use write_only option.
task_custom_id = serializers.CharField(write_only=True)
See the docs here https://www.django-rest-framework.org/api-guide/fields/#write_only
You just need to remove task_custom_id from the dictionary
class TimeReportCreateSerializer(serializers.ModelSerializer):
class Meta:
model = TimeReport
fields = (
'id',
'minutes_spent',
'reported_for',
'note',
'status',
'task_custom_id',
)
task_custom_id = serializers.CharField()
def create(self, validated_data):
user = User.objects.get(auth_user_id = self.context['user_id'])
task_custom_id = validated_data.pop("task_custom_id")
task = Task.objects.filter(custom_id = task_custom_id).filter(user = user.id).first()
report = TimeReport(**validated_data)
report.user = user
report.task = task
report.save()
return report
task = Task.objects.filter(custom_id = validated_data.pop('task_custom_id')).filter(user = user.id).first()
the **validated_data will return (task_custom_id=value, field1=value1 ...) and task_custom_id it's not a TimeReport field so all u need is to pop it from validated_data before calling the constructor TimeReport
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.
I'm writing an app that has an HTML page which must be capable of saving data into 2 models. I've created two separate forms and referenced them in the view, however the information is not saving into the DB.
Here are the views.py
def nuevoingreso(request):
if request.method == "POST":
formingreso = NuevoIngreso(request.POST)
formprodingreso = NuevoProdIngreso(request.POST)
if formingreso.is_valid():
ingreso = formingreso.save(commit=False)
ingreso.idUser = request.user
ingreso.Condominio = get_object_or_404(Condominios, idCondominio=request.session["idCondominio"])
ingreso.save()
ingresoprod = formprodingreso.save()
for i in range(5):
if ProductosIngresos.SubtotalP != "" and ProductosIngresos.IvaP != "" and ProductosIngresos.TotalP != "":
ingresoprod.ProductosIngresos(Concepto=request.POST.get("Concepto"+str(i), ""), SubtotalP=request.POST.get("SubtotalP"+str(i), ""), IvaP=request.POST.get("IvaP"+str(i), ""), TotalP=request.POST.get("TotalP"+str(i), ""))
ingresoprod.save()
return HttpResponseRedirect("/propiedades/")
else:
return render(request, "immovelc/nuevoingreso.html",
{"formingreso": formingreso, "formprodingreso": formprodingreso})
propiedadesing = PropiedadesCond.objects.all()
context = ({"propiedadesing": propiedadesing})
return render(request, "immovelc/nuevoingreso.html", context)
forms.py
class NuevoIngreso(ModelForm):
class Meta:
model = Ingresos
fields = ["Numero", "Persona", "Fecha", "Observaciones", "Cobrado", "Subtotal", "Iva", "Total"]
def clean(self):
Numero = self.cleaned_data["Numero"]
Persona = self.cleaned_data["Persona"]
Fecha = self.cleaned_data["Fecha"]
if not Numero:
raise forms.ValidationError("El campo de numero es obligatorio")
if not Persona:
raise forms.ValidationError("El campo de cliente es obligatorio")
if not Fecha:
raise forms.ValidationError("El campo de fecha es obligatorio")
class NuevoProdIngreso(ModelForm):
class Meta:
model = ProductosIngresos
fields = ["Concepto", "SubtotalP", "IvaP", "TotalP"]
models.py
class Ingresos(models.Model):
idIngreso = models.AutoField(primary_key=True, null=False, max_length=15)
idCondominio = models.ForeignKey(Condominios)
idUser = models.ForeignKey(User)
Numero = models.CharField(max_length=100)
Persona = models.CharField(max_length=250, default="Ninguno")
Cobrado = models.CharField(max_length=100, default=0)
Observaciones = models.TextField(default="Ninguna")
Fecha = models.DateField()
Subtotal = models.CharField(max_length=100)
Iva = models.CharField(max_length=100)
Total = models.CharField(max_length=100)
def __unicode__(self):
return unicode(self.idIngreso)
class ProductosIngresos(models.Model):
idProductoIngreso = models.AutoField(primary_key=True, null=False, max_length=15)
idIngreso = models.ForeignKey(Ingresos)
Concepto = models.CharField(max_length=500)
SubtotalP = models.CharField(max_length=100)
IvaP = models.CharField(max_length=100)
TotalP = models.CharField(max_length=100)
def __unicode__(self):
return unicode(self.idProductoIngreso)
Thanks!
No offence, but this code is far from being correct.
Besides you've got many errors that you might want to remove.
Errors:
formprodingreso.is_valid() is never called
inside for i in range(5) you use a class as if it was an instance (ProductosIngresos.SubtotalP)
clean method in form has to be outside the Meta block
I believe what you want inside the loop is:
producto_ingreso = ProductosIngresos()
producto_ingreso.idIngreso = ingreso # better change to producto_ingreso.ingreso
producto_ingreso.Concepto=request.POST.get("Concepto"+str(i), "") # producto_ingreso.concepto
producto_ingreso.SubtotalP=request.POST.get("SubtotalP"+str(i), "") # producto_ingreso.subtotal_p
producto_ingreso.IvaP=request.POST.get("IvaP"+str(i), "")
producto_ingreso.TotalP=request.POST.get("TotalP"+str(i), ""))
producto_ingreso.save()
To make it cleaner, you can make this king of logic overridding the save() method of ModelForm. Or use inline formsets.
Confusion:
Model FKs are objects in Django, not integers. Better name them like condominio instead of idCondominio
Decimal columns (subtotal, iva, total) should be declared as deciaml i.e. models.DecimalField(max_digits=10, decimal_places=2)
clean method is intended for cross field validation (more than one field). Only one field should be validated by clean_numero f.e.
Over complication:
models have ID/PK by default, no need to explicit them (referenced as self.id or self.pk)
model unicode function is not giving any info
clean and ValidationError are superflous: modelform checks if attributes are requiered automatically
Convention errors:
attributes are always written_in_lowercase (SubtotalP -> subtotal_p)
I would seriously try to fix all of those if you dont want the developers maintaining your code hate you and make some voodoo on you.
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()
edit: I completely rewrote the question as the original one didn't clearly explain my question
I want to run a function which is specific to each particular model instance.
Ideally I want something like this:
class MyModel(models.Model):
data = models.CharField(max_length=100)
perform_unique_action = models.FunctionField() #stores a function specific to this instance
x = MyModel(data='originalx', perform_unique_action=func_for_x)
x.perform_unique_action() #will do whatever is specified for instance x
y = MyModel(data='originaly', perform_unique_action=func_for_y)
y.perform_unique_action() #will do whatever is specified for instance y
However there is no datatype FunctionField. Normally this would be solvable with inheritance, and creating subclasses of MyModel, maybe like this:
class MyModel(models.Model):
data = models.CharField(max_length=100)
perform_unique_action = default_function
class MyModelX(MyModel):
perform_unique_action = function_X
class MyModelY(MyModel):
perform_unique_action = function_Y
x = MyModelX(data='originalx')
x.perform_unique_action() #will do whatever is specified for instance x
y = MyModelY(data='originaly')
y.perform_unique_action() #will do whatever is specified for instance y
Unfortunately, I don't think I can use inheritance because I am trying to access the function this way:
class MyModel(models.Model):
data = models.CharField(max_length=100)
perform_unique_action = default_function
class SecondModel(models.Model):
other_data = models.IntegerField()
mymodel = models.ForeignKey(MyModel)
secondmodel = SecondModel.objects.get(other_data=3)
secondmodel.mymodel.perform_unique_action()
The problem seems to be that I don't know what type the foreign key is going to be in SecondModel if I override the perform_unique_action in subclasses.
Can I access MyModel from SecondModel as a foreign key and still have a unique function for each instance of MyModel?
This works for me. I haven't tested it, but you should be able to create another class and override their methods and it'll work. Check the class Meta line, it'll treat it as an abstract class. Here's an example of my actual classes that I'm working on right now.
EDIT: Added VoteComment class and tested it. It works as expected!
class Vote(models.Model):
VOTE_ENUM = (
(VoteEnum.DOWN_VOTE, VoteEnum.toString(VoteEnum.DOWN_VOTE)),
(VoteEnum.NONE, VoteEnum.toString(VoteEnum.NONE)),
(VoteEnum.UP_VOTE, VoteEnum.toString(VoteEnum.UP_VOTE)),
)
question = models.ForeignKey(Question, null=False, editable=False, blank=False)
voter = models.ForeignKey(User, blank=False, null=False, editable=False)
vote_type = models.SmallIntegerField(default=0, null=False, blank=False, choices=VOTE_ENUM)
class Meta:
abstract = True
def is_upvote(self):
return self.vote_type > 0
def is_downvote(self):
return self.vote_type < 0
class VoteAnswer(Vote):
answer = models.ForeignKey(Answer, null=False, editable=False, blank=False)
class Meta:
unique_together = (("voter", "answer"),) # to prevent user from voting on the same question/answer/comment again
def __unicode__(self):
vote_type = "UP" if vote_type > 0 else ("DOWN" if vote_type < 0 else "NONE")
return u"{0}: [{1}] {2}".format(user.username, vote_type, answer.text[:32])
def is_upvote(self):
return "FOO! "+str(super(VoteAnswer, self).is_upvote())
class VoteComment(Vote):
comment = models.ForeignKey(Comment, null=False, editable=False, blank=False)
class Meta:
unique_together = (("voter", "comment"),) # to prevent user from voting on the same question/answer/comment again
def __unicode__(self):
vote_type = "UP" if vote_type > 0 else ("DOWN" if vote_type < 0 else "NONE")
return u"{0}: [{1}] {2}".format(user.username, vote_type, comment.text[:32])
def is_upvote(self):
return "BAR!"
I came up with two ways of having a specific function defined for each object. One was using marshal to create bytecode which can be stored in the database (not a good way), and the other was by storing a reference to the function to be run, as suggested by Randall. Here is my solution using a stored reference:
class MyModel(models.Model):
data = models.CharField(max_length=100)
action_module = models.CharField(max_length=100)
action_function = models.CharField(max_length=100)
class SecondModel(models.Model):
other_data = models.IntegerField()
mymodel = models.ForeignKey(MyModel)
secondmodel_obj = SecondModel.objects.get(other_data=3)
#The goal is to run a function specific to the instance
#of MyModel referred to in secondmodel_obj
module_name = secondmodel_obj.mymodel.action_module
func_name = secondmodel_obj.mymodel.action_function
module = __import__(module_name)
func = vars(module)[func_name]
func()
Thanks to everyone who replied, I couldn't have got to this answer if it weren't for your help.
You could achive some similar behavior overriding the save method. And providing special callbacks to your instances.
Something like:
def default_function(instance):
#do something with the model instance
class ParentModel(model.Model):
data = models.CharField()
callback_function = default_function
def save(self, *args, **kwargs):
if hasattr(self, 'callback_function'):
self.callback_function(self)
super(ParentModel, self).save(*args, **kwargs)
class ChildModel():
different_data = models.CharField()
callback_function = other_fun_specific_to_this_model
instance = ChildModel()
#Specific function to this particular instance
instance.callback_function = lambda inst: print inst.different_data
instance.save()
You can write endpoints on your server and limit their access to just your self. Then store in each model instance corresponding url. For example:
views.py
def funx_x(request):
pass
def func_y(request):
pass
models.py:
class MyModel(models.Model):
data = models.CharField(max_length=100)
perform_unique_action = models.URLField()
and then:
x = MyModel(data='originalx', perform_unique_action='http://localhost/funx_x')
requests.post(x.perform_unique_action)
i dont know whether i understand u correct or not. but you can check out this example here.
Example:
A string representing an attribute on the model. This behaves almost the same as the callable, but self in this context is the model instance. Here's a full model example:
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
def decade_born_in(self):
return self.birthday.strftime('%Y')[:3] + "0's"
decade_born_in.short_description = 'Birth decade'
class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'decade_born_in')