How do you find the database a Django object is using? - python

Django supports using multiple databases simultaneously, and the docs explain how to specify the database when saving or retrieving an object. However, given a Django model instance, how do you determine which database it's currently using? I've inspected an instance, but it doesn't seem to have any .using attribute or anything similar.

From the Using routers documentation, you can use model_instance._state.db to inspect the database which the current model instance is using.

Related

executing django model query?

In django model query, i want to know the sequential execution of it. Consider a query Blog.objects.get(name='palm').
In this where the Blog is defined, is that same as class blog in models.py?
What is objects i can't find anything related to this in source files of django. If Blog is a class, then what is the type of objects?
I want a development side concept. Can any one please explain how django makes these possible?
Every non-abstract Django model class has an attribute objects attached to it (unless you of course explicitly remove it).
object is a Manager. It is an object that has a lot of methods to construct queries that are then send to the database to fetch/store data.
So you first access the objects manager of the Blog class, next you call .get(name='palm') on it. This means that Django will translate this into a query. This depends on the database system you use. For instance if it is MySQL it will look like:
SELECT name, some, other columns
FROM app_blog
WHERE name = 'palm'
The database will respond with zero, one or more rows, and Django will, in case no or more than one row is found, raise a DoesNotExists or MultipleObjectsReturned error. Otherwise it will load the data into a Blog object (by deserializing the columns into Python objects).

How to use Django with existing database?

I want to create the admin for some tables of an existing MySQL dabatase. I want to use Django since it is just one line of code - admin.site.register(TableName) - so I save a lot of time coding the admin from scratch. I looked here for the inspectdb option of Django https://docs.djangoproject.com/en/1.5/howto/legacy-databases/ but only in the development version https://docs.djangoproject.com/en/dev/howto/legacy-databases/ says something about managing the inspected model. I want to know if it is possible and if somebody tried to work with an existing database before but not for read only, I want to manage and edit these database from my Django application.
If you're not using the development version, don't read the docs for that version. All they say is that - new in that version only - models created via inspectdb will by default be marked as managed = False, which means that they can't be modified. But the docs go on to describe exactly how you can modify them, simply by changing that setting.
But of course, you should be using the latest stable version, 1.5, which doesn't do that anyway. You can add and edit items in models from a legacy db to your heart's content.

Using Django ORM get_or_create with multiple databases

Django's ORM supports querying from a specific database (when multiple are defined in your project) via the .using() function for filter-based operations.
e.g. MyModel.objects.filter(name='Bob').using('my_non_default_database')
How would you do the equivalent when creating new records, via the class MyModel() or shortcut like get_or_create()?
using is a method on the MyModel.objects manager, so you can do
MyModel.objects.using('my_non_default_database').get_or_create(name="Bob")
If you have a MyModel instance, you can use the using keyword to specify the database to save to. The django docs point out some gotchas.
my_model = MyModel(name="Bob")
my_model.save(using='my_non_default_database')
using is just part of the standard query chain. So, you can use it anywhere before the query is sent to the DB. get_or_create, unlike filter, is atomic: when you call it, it does it's thing immediately, so you just need to call using before that.
MyModel.objects.using('my_non_default_database').get_or_create(name='Bob')

Python app to django web app

I've written some python code to accomplish a task. Currently, there are 4-5 classes that I'm storing in separate files. I'd now like to change this whole thing into a database-backed web app. I've been reading tutorials on Django, and so far I get the impression that I'll need to manually specify the fields and their types for every "model" that I use. This is a little surprising to me, since I was expecting some kind of ORM capability that would just take the existing classes I've already defined, and map them onto a database somehow, in a manner abstracted away from me.
Is this not the case? Am I missing something? It looks like I need to specify all the fields and types in the file 'models.py'.
Okay, now beyond those specifics, does anyone have any general tips on the best way to migrate an object-oriented desktop application to a web application?
Thanks!
That is Django's ORM: it maps classes to tables. What else did you expect? There needs to be some way of specifying what the fields are, though, before you can use them, and that's managed through the models.Model class and the various models.Field subclasses. You can certainly use your classes as mixins in order to use the existing business logic on top of the field definitions.
If you are thinking about a database backend based web app, you have to specify what fields of the data you want to store and what type of the value you want stored.
There is an abstraction that introspects the db to convert it into the django models.py format. But I know not of any that introspects a python class and stores arbitrary data into db. How would that even work? Are the objects, now, stored as a pickle?
You're going to have to check the output, but you can have Django automatically create models from existing databases through one-time introspection.
Taken from the link below, you would set up your database in settings.py, and then call
python manage.py inspectdb
This will dump the sample models.py file to standard out for your inspection. In order to create the file, simply redirect the output
python manage.py inspectdb > models.py
See for more:
http://docs.djangoproject.com/en/dev/howto/legacy-databases/?from=olddocs#auto-generate-the-models

Runtime model generation using django

I have an application that needs to generate its models on runtime.
This will be done according to the current database scheme.
How can it be done?
How can I create classes on runtime in python?
Should I create a json representation and save it in a database and then unserialize it into a python object?
You can try to read this http://code.djangoproject.com/wiki/DynamicModels
Here is example how to create python model class:
Person = type('Person', (models.Model,), {
'first_name': models.CharField(max_length=255),
'last_name': models.CharField(max_length=255),
})
You can also read about python meta classes:
- What is a metaclass in Python?
- http://www.ibm.com/developerworks/linux/library/l-pymeta.html
- http://gnosis.cx/publish/programming/metaclass_1.html
You could base yourself on the legacy database support of django which allows you to obtain django models from the definitions found in the database :
See here : http://docs.djangoproject.com/en/dev/howto/legacy-databases/?from=olddocs
In particular,
manage.py inspectdb
allows you to create the classes in a file. You should then be able to import them on the fly.
That said, it seems to me that you are on a risky path by doing this.
I have an application that needs to generate its models on runtime.
Take a look at the source code for the inspectdb management command. Inspectdb "Introspects the database tables in the database pointed-to by the NAME setting and outputs a Django model module (a models.py file) to standard output."
How can I create classes on runtime in python?
One way to do this is to use the functions provided by the new module (this module has been deprecated in favor of types since 2.6).
Should I create a json representation and save it in a database and then unserialize it into a python object?
This doesn't sound like a good idea to me.
PS: All said you ought to really rethink the premise for creating classes at runtime. It seems rather extreme for a web application. Just my 2c.

Categories

Resources