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)
Related
This is my code.
std_name = models.ForeignKey(
StudentInfo, on_delete=models.CASCADE)
def get_std_class_name(self):
return int(self.std_name.std_subject_class.std_class_name_N)
def limit_subject_std_choices():
return {'std_subject_class__std_class_name_N':'get_std_class_name' }
subject_name = models.ForeignKey(StdSubject,on_delete=models.CASCADE, limit_choices_to=limit_subject_std_choices)
But shows error. ValueError at /admin/results/studentinfo/1/change/ invalid literal for int() with base 10: 'get_std_class_name'
I dont know what is issue with my code. I wanna when any student put her marks any subject while subject will be showed base her class name.
Just I wanna get student class info from this model instance and pass a value within this function.
def limit_subject_std_choices():
return {'std_subject_class__std_class_name_N':'get_std_class_name'}
From the Django doc of limit_choices_to, the value should be a dict with an expression as key and the value as dict value
In your case, you are trying to find the values for each instance in your model, which is not possible.
Then what is possible in your case?
The std_subject_class__std_class_name_N expecting a PK value, (a integer value), so you should pass a valid integer as
subject_name = models.ForeignKey(StdSubject, on_delete=models.CASCADE,
limit_choices_to={'std_subject_class__std_class_name_N': 123})
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)
I have two one2many field which is reffering to a single model, existing in different models.
ie,
class modelA(models.Model):
_name = 'modela'
fila = fields.One2many('main','refa')
class moddelB(models.Model):
_name = 'modelb'
filb = fields.One2many('main','refb')
class main(models.Model):
_name = 'main'
name = fields.Char('Name')
date = fields.Date('Date')
refa = fields.Many2one('modela')
refb = fields.Many2one('modelb')
I will create records in modela. In this model there is a button is there. On clicking on that button i need to copy all values of fila field to filb field of modelb . How can i do that.
You need to use One2many values filling
XML code
<button name="copy2b" type="object" string="COPY"/>
Python code:
#api.multi
def copy2b(self):
for record in self:
filb_values = [(0, 0, {'name': line.name, 'date': line.date}) for line in record.fila]
vals = {'filb': filb_values}
# Just pass these values to `create` or `write` method to save them on `modelb`
for record in ids:
field_vals=[(0,0,{'product_name':line.product_id.name,'qty':line.quantity}) for line in record.invoice_line_ids]
vals={'inv_products':field_vals}
my_invoices=self.env["cron.invoice"].search([])
my_invoices.write(vals)
worked for me.
here, i am getting products from invoice_line_ids field of account.invoice model.
"for record in ids"
here ids is correspond invoice.
then i am loop through invoice using "record" thus i can access invoice_line_ids one2many field of invoice.
"inv_products" is my another one2many field in same model which is "cron.invoice".
before wrote into same model i had use create method for create some fields. then i can use search() method. which will return all crated records.
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})
I have a Django model with two different foreign keys to the same model. I have defined unique related_names for each field.
The problem occurs when I try to filter the class according to these fields.
This is the model I am working on:
class Foo(models.Model):
f_key1 = models.ForeignKey(Bar, related_name='key_1')
f_key2 = models.ForeignKey(Bar, related_name='key_2')
someNumber = models.IntegerField()
This is how I construct the filters:
list = Foo.objects.filter(Q(f_key1=bar1) | Q(f_key2=bar1)).order_by('-someNumber')[:3]
And this is the error message I get:
int() argument must be a string or a number, not 'ReverseSingleRelatedObjectDescriptor'
What am I doing wrong here?