Saturday, June 1, 2013

Re: SQL from Model ?


On Sat, Jun 1, 2013 at 11:24 AM, Josueh <josueh.cg@gmail.com> wrote:
hi!
is possible generate the SQL ("create table/index/....") in hardcode?
example:
class Book(models.Model):
    title = models.CharField(...)
    price = models.DecimalField(...)
print django_generate_sql_model( Book )  # <--- here

??   anyway?  idea?

It's certainly possible. After all, Django does it :-)

Depending on what you're trying to achieve, there are a couple of ways.

You can programatically invoke the syncdb command:

$ from django.core.management import call_command
$ call_command('syncdb')

This is exactly the same as calling ./manage.py syncdb from the command line

Alternatively, you can hook into the internals get the SQL that Django uses to drive the syncdb command. The key code is in django/core/management/sql.py; you can see how it's called by looking at django/core/management/commands/syncdb.py. Be warned: this is an undocumented internal interface. As a result, API consistency isn't guaranteed between releases. In practice, this doesn't really matter, because this part of the API is pretty stable, but it's worth keeping in mind.

The bigger question that needs to be asked, however, is *why* do you want to dynamically create models in this way. In my experience, this sort of dynamic model creation is almost always a bad idea, and much better solutions exist in having a more flexible, but static data model, or by using a data store more appropriate to the task (e.g., using a document-based store or a key-value store rather than a relational database). 

Before you spend too much time looking into dynamic model creation, I *really* encourage you to see if you can model the problem in a different way.

Yours,
Russ Magee %-)
 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment