Mongoengine: mongoengine.errors.FieldDoesNotExist - python

I've been confused with this error. I'm creating a Vehicle database with mongoengine that goes like this.
class Vehicles(Document):
make: StringField()
model: StringField()
license: StringField()
year: IntField()
mileage: IntField()
deleted: BooleanField()
for j in range(2):
vehicle = Vehicles(
make="Honda",
model="Civic",
license="H54 " + str(i) + str(j),
year=2015,
mileage= 500 + (i * 500),
deleted=False
).save()
While I try running the code, I've been getting:
mongoengine.errors.FieldDoesNotExist: The fields "{'license', 'year', 'model', 'mileage', 'make', 'deleted'}" do not exist on the document "Vehicles"
I don't understand why it's giving me this error. I know a solution is to change Document into DynamicDocument, but I don't really see why. Can someone please explain to me this error???

You are writing your class as if it was a dataclass but Mongoengine has no support for type hinting so it is not intepreting that correctly. MongoEngine is in fact currently not seeing any of your field definitions.
Turn your ":" into "=" and it should be fine
class Vehicles(Document):
make = StringField() # instead of 'make : StringField()'
...

Related

django Model.objects.create not immediately assign primary key to variable how to access that?

I have django Student model like below
class Student(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
score = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return f"Student(id: {self.id}, name: {self.name}, salary: {self.score})"
I have created some users in database also below is django shell output
>>> s = Student.objects.create(name="erik", score=90)
>>> print(s)
Student(id: None, name: erik, salary: 90) # <----- here is showing id None
>>> Student.objects.all()
<QuerySet [<Student: Student(id: 1, name: alex, salary: 40.00)>, <Student: Student(id: 2, name: john, salary: 60.00)>, <Student: Student(id: 3, name: erik, salary: 90.00)>]>
when i have called Student.objects.all() then it is showing id.
I want to get id from s variable because i am performing unit testing like below.
class GetSingleStudentTest(TestCase):
def setUp(self):
Student.objects.create(name="student1", score=50)
Student.objects.create(name="student2", score=55)
Student.objects.create(name="student3", score=80)
Student.objects.create(name="student4", score=36)
def test_get_single_student(self):
# get API response
response = client.get(reverse("student-detail", kwargs={"pk" : self.student2.pk }))
# get data from db
student = Student.objects.get(pk=self.student2.pk)
serializer = StudentSerializer(student)
self.assertEqual(response.data, serializer.data)
So when i have tried to access self.student2.pk it is None like we saw in django shell also. So how can i get that id?
because as i know Model.objects.create creates a user and also save into database then why id is None here? I am learning from this guide https://realpython.com/test-driven-development-of-a-django-restful-api/ but they not showed this kind of issues that's why I asked here. I have used setUpTestData method also but same kind of issue is there.
I think AutoField is working perfectly. Is it same as IntegerField but i have specified primary_key=True.
Thank you.
You need to save() the object so that pk is assigned. Also, you may refer to official doc at: https://docs.djangoproject.com/en/3.2/ref/models/instances/#auto-incrementing-primary-keys

How can you query embedded document that is null with mongoengine

I am new to mongoengine and querying. I got a document and an embedded document that looks like the following:
class Plan(EmbeddedDocument):
name = StringField()
size = FloatField()
class Test(Document):
date = DateTimeField()
plan = EmbeddedDocumentField(Plan)
How Can I get all Test-Documents that have no size set. That means that size=null/None?
I tried it with __raw__ query, but this did not work for me..
The way to query attribute of nested/embedded documents is done in the following manner (doc):
class LightSaber(EmbeddedDocument):
color = StringField()
length = FloatField()
class Jedi(Document):
name = StringField()
light_saber = EmbeddedDocumentField(LightSaber)
saber1 = LightSaber(color='red', length=32)
Jedi(name='Obiwan', light_saber=saber1).save()
saber2 = LightSaber(color='yellow', length=None)
Jedi(name='Yoda', light_saber=saber2).save()
Jedi(name='Rey', light_saber=None).save()
for jedi in Jedi.objects(light_saber__length=None):
print(jedi.name)
# prints:
# Yoda
# Rey
That being said, by naming your attribute "size", you are hitting an edge case. In fact "size" is a mongoengine operator and so if you query Test.objects(plan__size=None), you'll get an error because MongoEngine believes that you want to make use of the size operator.
To do the same with __raw__, you need to use the following:
for jedi in Jedi.objects(__raw__={'light_saber.length': None}):
print(jedi.name)
Using __raw__ works fine with "size" as well, in your example that would be: Test.objects(__raw__={'plan.size': None})

Get field value of inherited model Odoo 8

Hello to all I have been developing module under Odoo 8. I have a class "hrEmployee" with "_inherit=hr.employee" , now in my hrEmployee there is a One2many field having relation with another model "hr.employee.visa". I want to get the field values of the "hrEmployee" with onchange function defined on the field of "hr.employee.visa". Like when I change field value of "hrEmployee", I can get the field value entered on the current form (hrEmployee). How am I able to achieve this in Odoo v8? My Python code is shown below:
class hrEmployee(models.Model):
_inherit = "hr.employee"
diwan_no = fields.Char('Diwan No', size=30, help='Diwan Number')
zeo_number = fields.Char('ZEO Number',size=30, help='ZEO Number')
visas_ids = fields.One2many('hr.employee.visas', 'employee_id', 'Visas')
class hr_employee_visas(models.Model):
_name='hr.employee.visas'
employee_id = fields.Many2one("hr.employee.visas", "Employee" )
#api.onchange('visas_number')
#api.depends( 'visas_number')
def _visa_num(self):
cr=self._cr
uid=self._uid
ids=self._ids
for id in ids:
obj1=self.pool.get('hr.employee').browse(cr,uid,id,context=None)
print obj1.name_related
visas_sponsor = fields.Char('Sponsor')
visas_states = fields.Selection([('apply','Apply'),('active','Active'),('expire','Expire'),('cancel','Cancelled')], string='State' )
visas_number = fields.Char('Visa No', help='Visa Number')
I tried to use self.pool.get browse but it gives me "False" . Plz guide me or point me my mistake. Hopes for suggestion
Try following,
class hr_employee_visas(models.Model):
_name='hr.employee.visas'
employee_id = fields.Many2one("hr.employee", "Employee" )
#api.onchange('visas_number')
#api.depends( 'visas_number')
def _visa_num(self):
for obj in self:
print obj.employee_id.name
Here is the mistake
employee_id = fields.Many2one("hr.employee.visas", "Employee" )
You need to set hr.employee here.
No need to write both of the decorators together, in case of any changes into the visas_number field this method will be called, you can use any of the single decorator for this.

How do I get name from a many-to-many field in Django?

I am pretty new to Django.
I have the following code :
class ModelA(models.Model):
name = models.CharField(max_length=30)
class ModelB(models.Model):
name = models.ManytoManyField(ModelA)
colour = models.CharField(max_lenght=30)
iob = ModelB.objects.filter(name=name)
Now, this works fine :
for i in iob:
print i.colour
And I want to do something like :
for i in iob:
print i.name
But it doesnt work for sure. It outputs like :
<django.db.models.fields.related.ManyRelatedManager object at 0x30a2e50>
I want to print the value of name. How do I do this?
Since it is a many to many, you need to do:
for i in iob:
print i.colour
for obj_name in i.name.all()
print obj_name.name

Indexing not supported?

I get this error message:
TypeError: 'City' object does not support indexing
when this is my model:
class City(db.Model):
region = db.ReferenceProperty()
name = db.StringProperty()
image = db.BlobProperty()
vieworder = db.IntegerProperty()
areacode = db.IntegerProperty()
and this is my query
items = Item.all().filter('modified >', timeline).filter('published =', True).order('-modified').filter('cities =',city[0].key()).fetch(PAGESIZE + 1)`
Can you tell my how I should make my query or model my class definitions? I use listproperty(db.Key) to model relationships with references and I thought I could filter like the above query since it worked for one item. What should I do?
city[0].key()
is the cause of your error. Chances are you thought city was a list, but it's actually a single item, or some such.

Categories

Resources