Cannot convert instance of a document class to instance of its subclass - Mongoengine - mongodb

I am using Flask + mongoengine to create a web application. Here is a part of my models
class Order(Document):
placed_on=DateTimeField(required=True)
order_id = SequenceField()
status = StringField(default="Request Received")
cart = ListField(DictField())
userMobile = StringField(required=True)
userEmail = StringField(required=True)
address = ReferenceField(Address)
sheet_id = IntField(default=0)
remarks = StringField(default="")
meta = {'allow_inheritance': True}
class ConfirmedOrder(Order):
delivery_slot_start = DateTimeField()
delivery_slot_end = DateTimeField()
meta = {'allow_inheritance': True}
I have an instance of class Order as order. I now want to convert it to a ConfirmedOrder.This is the code I am using for the conversion
try:
order = Order.objects.get(id=order_id)
cOrder = ConfirmedOrder(**order.to_mongo())
cOrder.delivery_slot_start = timest
cOrder.delivery_slot_end = timend
cOrder.save();
except Exception as e:
print e
I However, get this error:
The field '_id' does not exist on the document 'Order.ConfirmedOrder'

Related

How to do this query using Django orm?

I have a Profile model and Complain model both are connected to the inbuilt User model.I have to do a query using both in which Profile model have residence. I want to have a count, that how many complains are made from a particular residence. I can do it using SQL but I didn't know how to do it using Django.
SELECT users_profile.residence,count(user_id)from users_profile INNER JOIN chp_complain on(users_profile.user_id = chp_complain.complain_user_id)GROUP BY(user_id)
Complain Model:-
class Complain(models.Model):
complain_user = models.ForeignKey(User, on_delete=models.CASCADE)
complain_department=models.CharField(max_length=100)
complain_subject = models.CharField(max_length = 100,help_text = "Enter the complain subject")
department_head=models.CharField(max_length=100)
recepient=models.CharField(max_length=100)
complain_description=models.TextField(max_length=2000)
date_posted = models.DateTimeField(default = timezone.now)
NOT_VISITED = 'NV'
VISITED = 'V'
INPROCESS = 'IP'
COMPLETED = 'C'
status = (
(NOT_VISITED, 'NV'),
(VISITED, 'V'),
(INPROCESS, 'IP'),
(COMPLETED, 'C'),)
status=models.CharField(max_length=2,choices=status,)
Profile Model:-
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
UID =models.CharField(max_length=30,default = "000",help_text = "'Staff's fill their STAFF ID and student's fill their ROLL NO " )
MALE = 'M'
FEMALE = 'F'
Gender=((MALE, 'Male'),(FEMALE, 'Female'),)
Gender=models.CharField(max_length=6,choices=Gender,default=MALE,)
FIRST = '1st'
SECOND = '2nd'
THIRD = '3rd'
FOURTH = '4th'
NGH = 'NGH'
NON_HOSTELER = 'Non_hosteler'
TEACHER_QUARTER = 'Teacher_quarter'
residence = ((FIRST, 'First'),(SECOND, 'Second'),(THIRD, 'Third'),(FOURTH, 'Fourth'),(NGH,'NGH'),(NON_HOSTELER, 'Non_hosteler'),(TEACHER_QUARTER,'Teacher_quarter'))
residence = models.CharField(max_length=20,choices=residence,default=FIRST,)
room_no=models.CharField(max_length=10,default = "000")
I want to have a count, that how many complains are made from a particular residence you can write:
Complain.objects.values('complain_user__profile__residence').annotate(complains_count=Count('id'))
In your SQL query:
SELECT users_profile.residence,count(user_id)from users_profile INNER JOIN chp_complain on(users_profile.user_id = chp_complain.complain_user_id)GROUP BY(user_id)
You calculate how many users filed complaints from a particular residence. It can be calculated as follows:
User.objects.values('profile__residence').annotate(Count('id'))

PSI update resource custom field with lookup table (Project Server)

Can someone show me a code to update a enterprise resource custom field with lookup table ? Already ran the internet looking for some sample code but did not succeed.
You can create and update a custom field with a lookup table using the below code . But we can not update or delete builtin custom fields
var projContext = new ProjectContext(projectServerUrl);
CustomFieldCollection CustomField = projContext.CustomFields;
EntityTypes Entitytype = projContext.EntityTypes;
LookupTableCollection lookupTables = projContext.LookupTables;
projContext.Load(CustomField);
projContext.Load(Entitytype);
projContext.Load(lookupTables);
projContext.ExecuteQuery();
CustomFieldCreationInformation NewfieldInfo = new CustomFieldCreationInformation();
NewfieldInfo.Id = new Guid();
NewfieldInfo.Name = "The Name";
NewfieldInfo.Description = "The Description";
NewfieldInfo.IsWorkflowControlled = true;
NewfieldInfo.IsRequired = true;
NewfieldInfo.IsEditableInVisibility = false;
NewfieldInfo.IsMultilineText = false;
LookupTable lookuptable = lookupTables.ToList().Find(x => x.Name == "LookupTableName");
projContext.Load(lookuptable);
projContext.ExecuteQuery();
NewfieldInfo.LookupTable = lookuptable;
NewfieldInfo.EntityType = Entitytype.ProjectEntity;
NewfieldInfo.FieldType = CustomFieldType.TEXT;
projContext.CustomFields.Add(NewfieldInfo);
projContext.CustomFields.Update();
projContext.ExecuteQuery();

MongoAlchemy query embedded documents

I want to know how to use MongoAlchemy about embeded docment operation.
But I havn't find any documents about these.
Can anyone give me some helps?
Here is demo code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Flask
from flaskext.mongoalchemy import MongoAlchemy
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['MONGOALCHEMY_DATABASE'] = 'book'
db = MongoAlchemy(app)
class Comment(db.Document):
user_id = db.StringField(db_field='uid')
posted = db.StringField(db_field='posted')
class Book(db.Document):
title = db.StringField()
author = db.StringField()
comments = db.ListField(db.DocumentField(Comment), db_field='Comments')
from mongoalchemy.session import Session
def test():
with Session.connect('book') as s:
s.clear_collection(Book)
save()
test_Book()
def save():
title = "Hello World"
author = 'me'
comment_a = Comment(user_id='user_a', posted='post_a')
comment_b = Comment(user_id='user_b', posted='post_b')
comments = [comment_a, comment_b]
book = Book(title=title, author=author, comments=comments)
book.save()
def test_Book():
book = Book.query.filter({'author':'me'}).first()
comment = book.comments[0]
comment.posted = str(book.comments[0].posted)+'_new'
book.save()
print 'change posted: Book.comments[0].posted:', book.comments[0].posted
comment_c = Comment(user_id='user_c', posted='post_c')
book.comments.append(comment_c)
book.save()
print 'append: Book.comments[2].posted:', book.comments[2].posted
query = Book.query.filter({Book.comments:{'$elemMatch':{Comment.user_id:'user_c'}}}).limit(1).first()
print 'query type:', type(query)
if __name__ == '__main__':
test()
I want to query data which user_id is "user_c", and just return back one Comment, How can I do that?
Does these methods below are MongoAlchemy remommended? BTW, these methods will return the whole document.
#query = Book.query.filter({Book.comments:{'uid':'user_c'}}).limit(1).first()
#query = Book.query_class(Comment).filter(Comment.user_id == 'user_c').limit(1).first()
#query = Book.query.filter({'comments':{'$elemMatch':{'uid':'user_c'}}}).limit(1).first()
#query = Book.query.filter({Book.comments:{'$elemMatch':{Comment.user_id:'user_c'}}}).limit(1).first()
How can I change "user_c" to "user_c_new" which find by query ?
How can I remove one comment which user_id is "user_b"?
Mongo doesn't support returning subdocuments. You can use $elemMatch to filter so that only documents with matching attributes are returned, but you'll have to grab the comments yourself. You could slightly optimize by only returning the comments field as follows:
query = Book.query.filter({Book.comments:{'$elemMatch':{Comment.user_id:'user_c'}}})
query = query.fields(Book.comments.elem_match({Comment.user_id:'user_c'}))
result = query.limit(1).first()
print 'query result:', result.comments
Note that there was a bug with this up until 0.14.3 (which I just released a few minutes ago) which would have caused results.comments not to work.
Another very important note is that the elem_match I'm doing there only returns the first matching element. If you want all matching elements you have to filter them yourself:
query = Book.query.filter({Book.comments:{'$elemMatch':{Comment.user_id:'user_c'}}})
result = query.limit(1).first()
print 'query result:', [c for c in result.comments if c.user_id == 'user_c']

Not able to fetch mongodb object with a valid field

I'm using Mongoengine.
When I do a:
>>> Grant.objects().first().client_id
The result is as expected.
ObjectId('526fd0da82353536892f22ae')
But, when I search based on the client_id,
>>> Grant.objects(client_id="526fd0da82353536892f22ae").first()
I get a InvalidQueryError:
InvalidQueryError: Cannot resolve field "client_id"
Here's what my Grant model looks like:
class Grant(db.Document):
#user_id = db.StringField()
user = db.ReferenceField(User)
client_id = db.StringField()
client = db.ReferenceField(Client)
code = db.StringField()
redirect_uri = db.StringField()
expires = db.DateTimeField()
scopes = db.ListField()
#for soft-deleting the grant
is_deleted = db.BooleanField(default=False)
#property
def user_id(self):
return self.user.id
#property
def client_id(self):
return self.client.id
def delete(self):
self.is_deleted = True
Can someone go through this code and point out the problem?
Do you try to use it like :
Grant.objects(client_id=ObjectId("526fd0da82353536892f22ae")).first()

How to search multi keywork in linq query

i have this code in homepage
CheckBox[] ch= new CheckBox[12];
ch[0] = ChkContextA;
ch[1]= ChkContextB;
ch[2]= ChkContextC;
ch[3]= ChkContextD;
ch[4]= ChkContextE;
ch[5]= ChkContextF;
ch[6]= ChkContextG;
ch[7]= ChkContextH;
ch[8]= ChkContextI;
ch[9]= ChkContextJ;
ch[10]= ChkContextK;
ch[11]= ChiContextL;
for (int i = 0; i < 11; i++)
if (ch[i].Checked) search += ch[i].Text + " ";
Response.Redirect("SearchEstate.aspx?content="+search);
and this code in SearchEstate
var content = Request.QueryString["content"];
RealEstateEntities db = new RealEstateEntities();
var query = from O in db.Owners
join E in db.Estates on O.OwnerID equals E.OwnerID
join P in db.Properties on E.PropertyID equals P.PropertyID
where P.Facilities.Contains(content)
select new
{
regdate = E.RegisterDate,
region = E.Region,
Estype = E.EstateType,
Fac = P.Facilities,
deal = P.DealType,
price = P.TotalCost,
img = E.Picture,
addrss = O.Address,
area = P.Area,
tel = P.TellNum,
bed = P.RoomNum,
park = P.ParikingNum
};
Repeater2.DataSource = query.OrderByDescending(x => x.regdate);
Repeater2.DataBind();
when user checked some checkbox "content" for example have this value:
SearchEstate.aspx?content=ContextB ContextE ContextJ
I Want search this values in Facility field in db
How can I do this? (Sorry for my bad English)
I have the feeling your are looking for something along the lines of this query:
var content = Request.QueryString["content"];
string[] contentArray = content.Split(' ');
//...
var query = //...
where P.Facilities.Any(f => contentArray.Contains(f.FacilityName))
//...
(or instead of FacilityName some other property of Facility)
But I am not sure.