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)
Related
I have a method of creating clien. one of the body fields of my method is client_users which is not in my client model. He has a foreign key for clients. I overwrite the create method and it is ok. But when I return the method I have this error:
AttributeError: Got AttributeError when attempting to get a value for field `clientes_usuarios` on serializer `ClienteCreateSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Cliente` instance.
Original exception text was: 'Cliente' object has no attribute 'clientes_usuarios'.
My field in my serializer:
class ClienteCreateSerializer(serializers.ModelSerializer):
endereco_residencial = EnderecoSerializer(read_only=False)
endereco_cobranca = EnderecoSerializer(read_only=False,required=False)
contatos = ContatoClienteSerializer(many=True, read_only=False, required=False)
certificados = CertificadoSerializer(many=True, read_only=False, required=False)
email = serializers.EmailField(source='usuario.email')
cnpj = serializers.CharField(max_length=14, min_length=14, source='usuario.cpf_cnpj')
foto = serializers.CharField(required=False)
data_abertura = serializers.DateField(input_formats=settings.DATE_INPUT_FORMATS, required=False, allow_null=True)
clientes_usuarios = UsuarioClienteCreateSerializer(many=True,read_only=False)
I have outher methods like this and they works fine
I have a model:
class Employee(models.Model, MyMixin):
full_name = models.CharField(max_length=255)
items = models.ManyToManyField(Item, blank=True)
and a mixin class:
class MyMixin(object):
def my_m2m(self, field):
field_value = getattr(self, field)
print(field_value)
// do something with many to many field
emp = Employee()
emp.my_m2m("items")
It gives me the result like employee.Item.None while printing emp.my_m2m("items")
on console.
If I do emp.items.all() it gives me the result but I cant get it by name.
Why is it not giving the list of item associated with it ?
Am I missing anything ?
As you say, adding .all() gives the result, so you need to add that to your dynamic lookup:
field_value = getattr(self, field).all()
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)
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})
Is it possible to override values inside a Model?
I am getting 'MyModel' object does not support item assignment.
my_model = MyModel.objects.get(id=1)
print my_model.title
if my_model.is_changed:
my_model['title'] = 'something' # 'MyModel' object does not support item assignment
params = {
'my_model': my_model,
...
}
return render(request, 'template.html', params)
Models are objects, not dictionaries. Set attributes on them directly:
if my_model.is_changed:
my_model.title = 'something'
Or, if the attribute name is dynamic, use setattr:
attr_name = 'title' # in practice this would be more complex
if my_model.is_changed:
setattr(my_model, attr_name, 'something')
This changes the in-memory copy of the model, but makes no database changes - for that your attribute would have to be a field and you'd have the call the save method on my_model. You don't need to do that if you just want to change what the template receives in its context, but just for completeness's sake:
if my_model.is_changed:
my_model.title = 'something'
my_model.save()
Dictionaries are mutable, if you actually have a dictionary:
mydict = {'title': 'foo'}
# legal
mydict['title'] = 'something'
But not everything is a dictionary.
Yes, you can change values, but this is not how its done. Django Models are Python classes that have models to represent fields. For example a CharField is for holding a string in a database. Let me demonstrate (code from django docs):
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
As you can see above the Python class is a custom Django model. It is linked to a databse, and when you run manage.py syncdb, it will interact with your database to create the tables and columns that you need it to.
Now, in your case:
if my_model.is_changed:
my_model.title = "Something"
my_model.save()
my_model is an object. So, try this:
if my_model.is_changed:
my_model.title = 'something'
my_model.save()
I was using inlineformset_factory, what I had to do was:
Instead of using my_model.title = 'something',
I had to use my_model.instance.title = 'something'
views.py
...
if request.method == "POST":
formset = modelName2(request.POST, instance=modelName1)
if formset.is_valid():
if changeInstance == True:
models = formset
# change the title if changeInstance is True
index = 0
model = models[index]
model.instance.title = "something else"
model.save()
...