I'm exporting data from a legacy Django application and have written a script that imports the old models.py, which are something like this:
class GeneralType(models.Model):
...
publications = models.ManyToManyField(Publication, blank=True)
class Publication(models.Model):
...
authors = models.TextField()
url = models.URLField(blank=True)
class Record(GeneralType):
...
name = models.CharField(max_length=128)
So, this should work:
for r in Record.objects.all():
for p in r.publications.all(): # Exception thrown here
print(p.url)
But instead it gives:
django.core.exceptions.FieldError: Cannot resolve keyword 'generaltype' into field. Choices are: authors, url
So, there's some issue with calling GeneralType methods on a Record instance, presumably related to having abstracted this out to a script, as everything is fine if similar code is run in the Django app.
There's probably something obvious I've missed here - would happen to know what it is?
Related
I have this architecture (very simplified)
from django.db import Models
class MainClass(models.Model):
a = models.IntegerField()
b = models.CharField()
class OtherClass(models.Model):
c = models.IntegerField()
main = models.OneToOneField(MainClass, primary_key=True)
Which means my MainClass object has an attribute named otherclass, because of the existence of the reverse relationship between these models.
My problem is if I specify valid values for MainClass.a and MainClass.b, but None for MainClass.otherclass. I get the error
ValueError: Cannot assign None: "MainClass.otherclass" does not allow null values.
I understand there cannot be OtherClass without MainClass (it doesn't make sense), but why the opposite situation is also causing an error? Other way: Why cannot be MainClass without OtherClass?
Looks like this is a normal behaviour in Django 1.8, although the restriction has been removed in Django 1.10
So, This isn't an error.
Hey I have coded CakePHP for a number of things but never ran into this problem before surprisingly. Also I have thoroughly searched the net and CakePHP docs and have not found an answer to my question. My question is, I have a table for my model that should be named Class, obviously I cannot use that name though since it's a reserved PHP keyword. What options do I have to be able to refer to this model appropriately.
So far I have;
Renamed my class model file to player_class.php
Renamed my class model class to PlayerClass
Changed var $name to 'PlayerClass'
Added to my class model class; var $useTable = 'classes';
Renamed my class controller to player_classes_controller.php
Renamed my class controller class to PlayerClassesController
Changed var $name to 'PlayerClasses'
While this does work, is this what has to be done or are to other options to be able to refer to it as Class still, like can I do any sort of mangling like _Class?
I once tested all CakePHP class names for Cake 1.2 if they can be used as Model names, here are the results:
NOT possible is:
app
appcontroller
appmodel
behaviorcollection
cache
cacheengine
cakelog
cakesession
classregistry
component
configure
connectionmanager
controller
datasource
debugger
dispatcher
file
fileengine
folder
helper
inflector
model
modelbehavior
object
overloadable
overloadable2
router
security
sessioncomponent
set
string
validation
Possible is:
acl
aclbase
aclbehavior
aclcomponent
aclnode
aclshell
aco
acoaction
admin
ajaxhelper
apcengine
apishell
app_model
apphelper
aro
authcomponent
bake
baker
bakeshell
behavior
cachehelper
cake
cakeschema
cakesocket
consoleshell
containablebehavior
controllertask
cookiecomponent
dbacl
dbaclschema
dbconfigtask
dboadodb
dbodb2
dbofirebird
dbomssql
dbomysql
dbomysqlbase
dbomysqli
dboodbc
dbooracle
dbopostgres
dbosource
dbosqlite
dbosybase
element
emailcomponent
error
errorhandler
extracttask
flay
formhelper
htmlhelper
httpsocket
i18n
i18nmodel
i18nschema
i18nshell
iniacl
javascripthelper
jshelper
jshelperobject
l10n
layout
magicdb
magicfileresource
mediaview
memcacheengine
modeltask
multibyte
numberhelper
page
pagescontroller
paginatorhelper
permission
plugintask
projecttask
requesthandlercomponent
rsshelper
sanitize
scaffold
schema
schemashell
securitycomponent
sessionhelper
sessionsschema
shell
shelldispatcher
test
testsuiteshell
testtask
texthelper
themeview
timehelper
translate
translatebehavior
treebehavior
viewtask
xcacheengine
xml
xmlelement
xmlhelper
xmlmanager
xmlnode
xmltextnode
When i run into this sort of problem i usually do what you did, only i prefix the reserved word with "My" (so when i read the code it doesn't look like that class has anything to do with "Player"... for example, just the other day i wanted to model a "ACO" model.. but that already existed in cake (same scenario of reserved word) so i created a model called Myaco.
I think you should just name it Myclass.
Regarding the model name and controller name changes- i think you did good, i would do the same. Your only real option is to use the $useTable = 'classed'; to use your DB table.
If you use the underscore prefix, i believe cake will not be able to handle it (it will fail in the Inflector class).
Good luck
I can second that solution. I had the same problem and used a prefix that was the initials of the client. Ended up calling mine Dtclass. Unfortunately, it took me an hour or so to figure out what the problem was. One of those cases where the answer stares you in the face all the time till you finally recognize it.
When separating the API classes into multiple files, the API explorer shows the same request definition for all resources.
So based on the structure shown below (my apologies if it's too long), in the API explorer, both my_api.api_a.test and my_api.api_b.test show the same attribute, attr_b, which is the last in the api_server list definition. If I change it and put ApiA last, then both methods show attr_a.
Any idea what am I doing wrong
# model/model_a.py
class A(EndpointsModel):
attr_a = ndb.StringProperty()
# model/model_b.py
class B(EndpointsModel):
attr_b = ndb.StringProperty()
# api/__init__.py
my_api = endpoints.api(name='my_api', version='v1')
# api/api_a.py
#my_api.api_class(resource_name='api_a')
class ApiA(remote.Service):
#A.method(name='test', ...)
...
# api/api_b.py
#my_api.api_class(resource_name='api_b')
class ApiB(remote.Service):
#B.method(name='test', ...)
...
# services.py
from api import my_api
application = endpoints.api_server([ApiA, ApiB])
Also tried to define the api_server as shown below, but didn't work at all.
application = endpoints.api_server([my_api])
I've noticed similar issues (which might be a bug in the endpoints-proto-datastore libary) when the actual method names (not the name in the decorator) are the same in different api classes.
Doesn't work:
class ApiA(remote.Service):
#A.method(...)
def test(self, model):
...
class ApiB(remote.Service):
#B.method(...)
def test(self, model):
...
Works:
class ApiA(remote.Service):
#A.method(...)
def test_a(self, model):
...
class ApiB(remote.Service):
#B.method(...)
def test_b(self, model):
...
You skipped those lines in your sample, but the behaviour you state matches what I encountered in this scenario.
Maybe my question is somehow unspecific, sorry for that. I'm learning python and app engine (webapp2) at the moment.
I have this class:
class Ice(db.Model):
"""Models an individual Guestbook entry with an author, content, and date."""
name = db.StringProperty()
description = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
def getTags(self):
return Tag.all().ancestor(self).fetch(10)
Tags are referenced via ancestor.
When I use a jinja-template i can call ice.getTags() foreach Ice.
Now i want to serialize my Ice-object to JSON and want to have all Tags that belong to the Ice-object in my JSON-Output.
This does serialisation for me:
It works okay, but it doesn't include the Tags.
I'm feeling, that i have to declare Tags as Ice-Attribute, but i don't know how.
class IceHandler(basehandler.BaseHandler):
def get(self):
ice_query = model.Ice.all().order('-date')
ices = ice_query.fetch(10)
self.response.write(json.encode(ices))
Thanks!
I seem to have a problem after creating an unmanaged model (syncdb):
class Client_jobs(models.Model):
job_id = models.IntegerField(primary_key=True)
status = models.IntegerField()
class Meta:
db_table = 'client_jobs'
managed=False
in one of my def views, it calls the database view(Client_jobs)
def listjobs(request):
# if user is authenticated
if request.user.is_authenticated():
jobsArr = Client_jobs.objects.get.all()
The page returned me an error of
(1146, "Table 'table1.client_jobs' doesn't exist")
I know I'm missing something but I can't figure out. How does django detect this unmanaged model? Thank you.
as I know the db_table option will get precedence over the existing convention of app name_model name. If you set it explicitly you will have to prefix the application name yourself.
try client_jobs.client_jobs