I have a model:
class Tasks(models.Model):
name = models.CharField(max_length = 50, null = True, blank = True)
assigned_to = models.ManyToManyField(User, null = True, blank = True)
I have to execute a query
tasks_for_myuser = Tasks.objects.filter(assigend_to__contains = myuser)
But this is throwing an error.
django.core.exceptions.FieldError: Related Field got invalid lookup: contains
Please help!
If you are trying to filter Tasks which has assigned_to field set to myuser, you can simply query like this.
tasks_for_myuser = Tasks.objects.filter(assigend_to = myuser)
You don't really require contains here, since it is a many-to-many field.
Related
After running this code, the data will be inserted into the database. when I check the database, I find a row added with values: int_field=0 and other="" (empty string)
My question is how to throw exception in case of Null/empty insert.
from datetime import datetime
db = pw.MySQLDatabase('tests', user = 'root', password = 'root', host = 'localhost', port = 3306)
class Model(pw.Model):
name = pw.CharField()
created_at = pw.DateTimeField(default = datetime.now())
other = pw.CharField(null = False)
int_field = pw.IntegerField(null = False)
class Meta:
database = db
db_table = 'nmodel'
Model.create_table()
Model.create(name = "tests")
Its a MySQL strict_mode issue, you should enable it in peewee Database Instance Like below.
Add this (sql_mode='STRICT_ALL_TABLES') to the constrcutor call:
db=pw.MySQLDatabase('database_name', user='user_name', password='user_psswd',
host='host_name', port=port_num,sql_mode='STRICT_ALL_TABLES')
This will throw a mysql exception when null values are passed.
I think you need to set your sql_mode to be more strict. See:
https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sql-mode-setting
Specifically, I think you're running into:
https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sqlmode_no_auto_value_on_zero
I have the following structures:
class UserOther(ndb.Model):
other_type = ndb.StringProperty(indexed = True)
other_data = ndb.StringProperty(indexed = False)
class User(ndb.Model):
name = ndb.StringProperty(default = "NULL", indexed = False)
email = ndb.StringProperty(default = "NULL", indexed = False)
active = ndb.BooleanProperty(default = True)
others = ndb.StructuredProperty(UserOther, repeated = True)
updated_at = ndb.DateTimeProperty(auto_now = True)
How can I use an User key id and a string for other_type(like "job") to get and be able to edit that information. I tried using the ancestor parameter, but perhaps I didn't do that correctly.
user_key = ndb.Key("User", user_id)
user = user_key.get()
other = UserOther.query(UserOther.other_type == "job", ancestor = user_key).get()
So if i print my user looks like this :
1425436064.0User(key=Key('User', 5171003185430528), active=True, email=u'NULL', name=u'NULL', others=[UserOther(other_data=u'0', other_type=u'job'), UserOther(other_data=u'0', other_type=u'times_worked'), UserOther(other_data=u'0', other_type=u'times_opened')], updated_at=datetime.datetime(2015, 3, 6, 10, 35, 24, 838078))
But if I print the job variable it is
1425436759.0None
You've misunderstood how to query for structured properties. The UserOther entity doesn't live on its own, it's part of the relevant User entity, so that's what you need to query.
The documentation explains exactly how to do this, but in summary you would do:
job = User.query(User.others.other_type == "job").get()
What I would do is get the user (by id) and then filter the 'others' in code:
user = User.get_by_id(user_key_id)
for other in user.others:
if other.other_type == 'job':
print other.other_data # do edits
What's wrong with my query?
Here are my models:
class Positions(ndb.Model):
title = ndb.StringProperty(indexed=True)
summary = ndb.TextProperty()
duties = ndb.TextProperty()
dateCreated = ndb.DateTimeProperty(auto_now_add=True)
dateUpdated = ndb.DateTimeProperty(auto_now=True)
class Applicants(ndb.Model):
name = ndb.StringProperty(indexed=True)
position = ndb.KeyProperty(kind=Positions,repeated=True)
file = ndb.BlobKeyProperty()
dateCreated = ndb.DateTimeProperty(auto_now_add=True)
dateUpdated = ndb.DateTimeProperty(auto_now=True)
Here is my query:
class AdminPositionInfoHandler(BaseHandler):
def get(self,positionKeyId):
user = users.get_current_user()
if users.is_current_user_admin():
positionKey = ndb.Key('Positions',int(positionKeyId))
position = positionKey.get()
applicants = Applicants.query(position=position.key).fetch() # the query
values = {
'position': position,
'applicants': applicants,
}
self.render_html('admin-position-info.html',values)
else:
self.redirect(users.create_login_url(self.request.uri))
What seems to be wrong in using the query:
applicants = Applicants.query(position=position.key).fetch()
I got this error:
File "C:\xampp\htdocs\angelstouch\main.py", line 212, in get
applicants = Applicants.query(position=position.key).fetch()
...
TypeError: __init__() got an unexpected keyword argument 'position'
I also tried using positionKey instead of position.key:
applicants = Applicants.query(position=positionKey).fetch()
I got this from "Ancestor Queries" section of GAE site:
https://developers.google.com/appengine/docs/python/ndb/queries
You don't pass arguments to query like that - ndb uses overridden equality/inequality operators, so you can express queries more 'naturally', with '==', '<', '>' etc., so:
applicants = Applicants.query(Applications.position==position.key).fetch()
The section in the on Filtering by Property Values gives some more examples.
(ancestor is a special-case for queries - it isn't a model property)
I have a trigger that moves the values from one object to another, but am stuck on how to move the values of the lookup fields from one to the other. what is the syntax? If you could show me the Company and the Chair_Rep ones that would be great!
<Lead> newLeadsList= new List<Lead>();
for (integer i=0; i<newContacts.size(); i++) {
if (newContacts[i].createlead__c == TRUE && oldContacts[i].createlead__c == FALSE ) {
newLeadsList.add(new Lead(
firstName = newContacts[i].firstName,
lastName = newContacts[i].lastName,
***Company = newContacts[i].account.name,***
Status = 'identified',
LeadSource = newContacts[i].leadsource ,
Product_Interest__c = 'CE',
//ContactLink__c = newContacts[i].ID,
Title = newContacts[i].title,
Email = newContacts[i].email,
//***Chair_Rep__c = newContacts[i].Chair_Rep__c***
Phone = newContacts[i].Phone,
MobilePhone = newContacts[i].MobilePhone,
// Address = newContacts[i].MailingAddress,
//Website = newContacts[i].Website,
nickname__c = newContacts[i].Nickname__c
Lookup fields should contain references (IDs) on records.
Is 'Company' a standard Lead field in your code?
***Company = newContacts[i].account.name,***
If so, then it's a Text(255) type field, which cannot be used as lookup.
If you need to make a lookup on a Contact's account record, then you can create a custom Lookup field on Lead with reference to Account. And then you could try this code (assuming ContactCompany is that custom lookup field :
ContactCompany__c = newContacts[i].AccountId
or
ContactCompany__c = newContacts[i].Account.Id
Chair_Rep__c and newContacts.Chair_Rep__c should be lookup fields on same object. Then this
Chair_Rep__c = newContacts[i].Chair_Rep__c
or this should work
Chair_Rep__c = newContacts[i].Chair_Rep__r.Id
I have such data stored in database:
class DeleteMe(db.model):
value1 = IntegerProperty(required = True, indexed = False)
And want to migrate it to such schema:
class DeleteMe(db.model):
value1 = IntegerProperty(required = True, indexed = False)
value2 = IntegerProperty(required = True, indexed = False)
What is the easiest method to migrate?
I found that I can do this in such way but it slow and error generating.
First create new table without required:
class DeleteMe(db.model):
value1 = IntegerProperty(required = True, indexed = False)
value2 = IntegerProperty(required = False, indexed = False)
Second update all records.
Third switch target model with required:
class DeleteMe(db.model):
value1 = IntegerProperty(required = True, indexed = False)
value2 = IntegerProperty(required = True, indexed = False)
It is slow so I think that I am not doing it correctly or app engine not allows it? Please help to find good way.
You don't have to do all that. You simply add the new required field and update all the records that don't have the value2 with a default value. Your application will work without any issues for the entities that don't have the value2 initialized.
I would suggest you to add a default value, if possible to have it, so in case you will update other values in the entity without touching the value2 the application will not crash.
Also don't forget that if you don't update the old entities (by explicitly editing and storing the value) even if you'll have set the default value if you query on the value2 the old entities won't be included in the result.