Save data in Models where field name comes from a variable - python

I want to save data in models where fieldname stored in a variable but while storing it is giving error of invalid keyword argument
my code :
field = request.POST['creationLanguage']
title = Translation.objects.create(field = request.POST['title'])
Here field stores the field name for model Translation but how I store data with this dynamic field_name .

Use the kwargs magic:
field = request.POST['creationLanguage']
value = request.POST['title']
title = Translation.objects.create(**{field: value})

Related

How to set the default value without a related field in odoov11?

I would need to set the value of the 'overtime_w' field as the default value for the 'overtime_w_edit' field without a related field.
overtime_w = fields.Float(compute='_compute_t_overtime_w')
overtime_w_edit = fields.Float()

Unable to edit the django table

Unable to perform the update operation.
This function is for table update, but the code is not allowing me to pass the instance in the form because it is not a model form. Please suggest the changes.
class userForm(forms.Form):
SHIFT_CHOICES = ( ('D','DAY'), ('N','NIGHT') )
ADMISSION_FORM_STATUS = ( ('Y','YES'), ('N','NO') )
FORM_COMPLETE_STATUS = ( ('Y','YES'), ('N','NO'))
TRAINING_STATUS = ( ('Y','YES'), ('N','NO') )
STATUS = ( ('W','WORKING'), ('OL','ON_LEAVE'), ('E','EXIT') )
employee_id = forms.CharField(max_length=8,required=False)
employer_id = CompanyModelChoiceField(required=False, queryset=Company.objects.all(), label='Employer', widget=Select2Widget)
name = forms.CharField(max_length=255)
uber_name = forms.CharField(max_length=255, required=False)
mobile = forms.CharField(max_length=20, required=False)
To bind data with the form fields, (not a model form), you will have to pass a dictionary with those specific fields to the form constructor.
In this case what you need to do is
Get the form data in a dictionary
driver = Driver.objects.get(employee_id = employee_id)
form_data = {'employee_id':driver.employee_id, 'employer_id', driver.employer_id, .., .., .} #all the fields in the form
AddDriverForm(initial=form_data)
Then while saving the data you should do it the same way you did for creating the driver.
Moreover, I would personally suggest you to use Model form for this case since you are going to put that data in the model anyways, it will surely save you the hassle.
Also, you might consider to normalize your model if its not a big deal.
Lets say your model (DC) has an instance (an entry):
Superhero = Bruce, Butler = Alfred, Engineer = Lucius, car = Batmobile
Your form has
Superhero, Butler, Engineer
(Notice that my form is missing the car field)
Now, suppose you want to change the name Butler to Jarvis
instance = DC.objects.get(id=8) #lets consider this as the id of the instance we have
#what you need to do is save the required data in a dictionary in this case
form_data = {'Superhero':instance.Superhero, 'Butler':instance.Butler, 'Engineer': instance.Engineer } #we haven't passed the car field
#Also I think that passing extra fields must not be an issue but I haven't tried
UpdateForm(form_data)
This will render the data properly when the form is displayed.

How to get the value of a Django Model Field object

I got a model field object using field_object = MyModel._meta.get_field(field_name). How can I get the value (content) of the field object?
Use value_from_object:
field_name = 'name'
obj = MyModel.objects.first()
field_object = MyModel._meta.get_field(field_name)
field_value = field_object.value_from_object(obj)
Which is the same as getattr:
field_name = 'name'
obj = MyModel.objects.first()
field_object = MyModel._meta.get_field(field_name)
field_value = getattr(obj, field_object.attname)
Or if you know the field name and just want to get value using field name, you do not need to retrieve field object firstly:
field_name = 'name'
obj = MyModel.objects.first()
field_value = getattr(obj, field_name)
Assuming you have a model as,
class SampleModel(models.Model):
name = models.CharField(max_length=120)
Then you will get the value of name field of model instance by,
sample_instance = SampleModel.objects.get(id=1)
value_of_name = sample_instance.name
If you want to access it somewhere outside the model You can get it after making an object the Model. Using like this
OUSIDE THE MODEL CLAA:
myModal = MyModel.objects.all()
print(myModel.field_object)
USING INSIDE MODEL CLASS
If you're using it inside class you can simply get it like this
print(self.field_object)
Here is another solution to return the nth field of a model where all you know is the Model's name. In the below solution the [1] field is the field after pk/id.
model_obj = Model.objects.get(pk=pk)
field_name = model_obj._meta.fields[1].name
object_field_value = getattr(model_obj, field_name)

Django: ValueError when saving an instance to a ForeignKey Field

I am trying to save an instance of a model but get a ValueError.
ValueError: Cannot assign "<DataPointModel: DataPointModel object>":
"Bike.data_point" must be a "DataPointModel" instance.
The model has a very simple field:
data_point = models.ForeignKey(DataPointModel, null=True, blank=True)
And the method is as well.
data_point = DataPointModel.objects.filter(
object_id=bike.reference_model.id,
).last()
watch.data_point = data_point
watch.save()
Why is this not saving?
Whenever you update or create anything in the table contains foreign Key you need to pass the object of primary key instead of passing real value.So you have to call the get query to primary key value table then pass that obj to foreign key column as a value.
Example :-
Suppose I have two model as follows:-
class model1(models.Model):
name=models.CharField(primary_key=True,,max_length=2000)
className=models.CharField(max_length=2000,null=True)
class model2(models.Model):
name=models.ForeignKey(model1)
teacher=models.CharField(max_length=2000,null=True)
views.py:-
jimmy = model2.objects.get(name="Jimmy")
obj = model1.objects.get(name='Piyush')
model2.objects.filter(id=jimmy.id).update(teacher=obj)

NDB: Query for unset properties?

I've had some data being gathered in production for a couple of days with, lets say, the following model:
class Tags(ndb.Model):
dt_added = ndb.DateTimeProperty(auto_now_add=True)
s_name = ndb.StringProperty(required=True, indexed=True)
Imagine I now add a new property to the model:
class Foo(ndb.Model):
is_valid = ndb.BooleanProperty(default=False)
some_key = ndb.KeyProperty(repeated=True)
class Tags(ndb.Model):
dt_added = ndb.DateTimeProperty(auto_now_add=True)
name = ndb.StringProperty(required=True, indexed=True)
new_prop = ndb.StructuredProperty(Foo)
... and gather some more data with this new model.
So now I have a portion of data that has the property new_prop set, and another portion that does not have it set.
My question is: how to I query for the data with the new property new_prop NOT set?
I've tried:
query_tags = Tags.query(Tags.new_prop == None).fetch()
But does not seem to get the data without that property set... Any suggestions?
Thanks!
The Datastore distinguishes between an entity that does not possess a property and one that possesses the property with a null value (None).
It is not possible to query for entities that are specifically lacking a given property. One alternative is to define a fixed (modeled) property with a default value of None, then filter for entities with None as the value of that property.

Categories