I saw the question can i use a database view as a model in django and tried it in my app, but that didn't work.
I created a view named "vi\_topics" manually and it had "id" column but I kept getting an error, even if I added "id" field explicitly, saying
"no such column: vi_topics.id"
Here is the definition of my model named Vitopic:
from django.db import models
class Vitopic(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author_name = models.CharField(max_length=200)
author_email = models.CharField(max_length=200)
view_count = models.IntegerField(default=0)
replay_count = models.IntegerField(default=0)
tags = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'vi_topics'
Note: I use sqlite3.
Try this:
http://docs.djangoproject.com/en/dev/ref/models/options/#managed
managed
Options.managed
New in Django 1.1: Please, see the release notes
Defaults to True, meaning Django will create the appropriate database tables in syncdb and remove them as part of a reset management command. That is, Django manages the database tables' lifecycles.
If False, no database table creation or deletion operations will be performed for this model. This is useful if the model represents an existing table or a database view that has been created by some other means. This is the only difference when managed is False. All other aspects of model handling are exactly the same as normal. This includes
Adding an automatic primary key field to the model if you don't declare it. To avoid confusion for later code readers, it's recommended to specify all the columns from the database table you are modeling when using unmanaged models.
If a model with managed=False contains a ManyToManyField that points to another unmanaged model, then the intermediate table for the many-to-many join will also not be created. However, a the intermediary table between one managed and one unmanaged model will be created.
If you need to change this default behavior, create the intermediary table as an explicit model (with managed set as needed) and use the ManyToManyField.through attribute to make the relation use your custom model.
For tests involving models with managed=False, it's up to you to ensure the correct tables are created as part of the test setup.
id = models.IntegerField(primary_key=True)
Related
I am learning Django. I am creating app where I have a model Employer.
In a database, I want to keep only one record for fields user and website.
I tried to use unique_together in my model but during migration I got the following error:
django.db.utils.IntegrityError: UNIQUE constraint failed: employer_employer.user_id, employer_employer.website
Can you please advice me what is a problem? Maybe this is not a good way how to do it?
Thanks!
class Employer(models.Model):
USER = settings.AUTH_USER_MODEL
user = models.ForeignKey(USER, default=1, on_delete=models.CASCADE)
company_name = models.CharField(max_length=200)
company_size = models.IntegerField(default=0)
website = models.CharField(max_length=200)
class Meta:
unique_together = ('user', 'website')
I tried to use unique_together in my model but during migration I got the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: employer_employer.user_id, employer_employer.website
This means the migration is perfectly fine. It means there is already data in the database that violates the constraint, so you will first need to go through the fact that there are Employer objects in the database with the same user and the same website.
You can find such Users effectively with:
from django.db.models import Count
Employee.objects.values('user', 'website').annotate(count=Count('pk')).filter(
count__gt=1
)
then you will have to fix these Employer records.
Note: As the documentation on unique_together [Django-doc] says, the unique_together constraint will likely become deprecated. The documentation advises to use the UniqueConstraint [Django-doc] from Django's constraint
framework.
I am having trouble understanding how the model class can create a table in the database.
If I wanted a table with fields users and password, wherein CakePHP do I define these fields? It seems like, in the examples I've seen, that these fields are validated in the model. But where are they defined or initialized?
Thanks.
CakePHP models don't create the database tables for you. They are a means of accessing existing tables that you have created. If you follow CakePHP's naming conventions the models just automatically know which tables they relate to; singular CamelCased model names relate to plural snake_cased tables.
To create your database tables you can either do this manually, or use CakePHP schemas to manage the database structure. There's also the excellent CakeDC migrations plugin for managing changes to the database structure.
CakePHP Schema management
CakeDC Migrations plugin
When a model is used in CakePHP it can determine the fields that belong to the model by running a SQL DESCRIBE query on the database table. This is done using the Model::schema() method. Cake caches the query results so that it doesn't need to keep querying the database for this.
Yes , sure , You can control database's table with its fields ,Model name should be the same of table name , in any controller you can load
$this->loadModel('SomeModel')
$mydata=$this->tableName->find('all');
$myuse =$this->set('myuse' , $mydata);
in your view , The name of view should be the same of your Controller's function name:
<h1> <?php echo $myuse['tableName']['fieldName]; ?></h1>
It not required to same name model as database table
like my table name is users and i create a model User
then you can define this table with User model in model > User.php
<?php
App::uses('AppModel', 'Model');
class User extends AppModel
{
public $name = 'User';
public $useTable = 'users';
public $primaryKey = 'id';
}
Changing question. I Want to apply ManyToMany relationship between db.Model and NDB.
example
NDB model
class my_NDB(search.SearchableModel):
.......
.......
db model
class Test(search.SearchableModel):
email = db.StringProperty()
created_by = db.IntegerProperty()
Can I apply ManyToMany relationship between these models?
EDIT:
Here is my User Model
class User(model.Expando):
"""Stores user authentication credentials or authorization ids."""
#: The model used to ensure uniqueness.
unique_model = Unique
#: The model used to store tokens.
token_model = UserToken
created = model.DateTimeProperty(auto_now_add=True)
updated = model.DateTimeProperty(auto_now=True)
# ID for third party authentication, e.g. 'google:username'. UNIQUE.
auth_ids = model.StringProperty(repeated=True)
# Hashed password. Not required because third party authentication
# doesn't use password.
email = model.StringProperty(required=True)
is_active = model.BooleanProperty(required=True)
password = model.StringProperty()
And Here is my Test db model
class Test(search.SearchableModel):
email = db.StringProperty()
created_by = db.IntegerProperty()
Now I want to apply manyToMany on Test. Is it possible?
Django style ManyToMany
created_by = models.ManyToManyField(User)
I see. I had to look up the Django ManyToManyField docs. IIUC you want a Test to be created by multiple users, and of course each user can create multiple tests. Have I got that right?
The way to do this would be to have a db.ListProperty(db.Key) in the Test class, so that the Test class has a list of keys -- where the keys point to User entities.
Now your User model is an NDB class, which complicates matters a bit. However the ndb Key class has an API for converting to and from db Keys:
If you have an ndb Key k, k.to_old_key() returns the corresponding db.Key.
If you have a db Key k, ndb.Key.from_old_key(k) returns the ndb.Key for it (it's a class method).
Hope this helps. Good luck!
PS. Please update your code to use from google.appengine.ext import ndb so you can write ndb.Expando, ndb.StringProperty, etc.
I'm just starting to get my head around non-relational databases, so I'd like to ask some help with converting these traditional SQL/django models into Google App Engine model(s).
The example is for event listings, where each event has a category, belongs to a venue, and a venue has a number of photos attached to it.
In django, I would model the data like this:
class Event(models.Model)
title = models.CharField()
start = models.DatetimeField()
category = models.ForeignKey(Category)
venue = models.ForeignKey(Venue)
class Category(models.Model):
name= models.CharField()
class Venue (models.Model):
name = models.CharField()
address = models.CharField()
class Photo(models.Model):
venue = models.ForeignKey(Venue)
source = models.CharField()
How would I accomplish the equivalent with App Engine models?
There's nothing here that must be de-normalized to work with App Engine. You can change ForeignKey to ReferenceProperty, CharField to StringProperty and DatetimeField to DateTimeProperty and be done. It might be more efficient to store category as a string rather than a reference, but this depends on usage context.
Denormalization becomes important when you start designing queries. Unlike traditional SQL, you can't write ad-hoc queries that have access to every row of every table. Anything you want to query for must be satisfied by an index. If you're running queries today that depend on table scans and complex joins, you'll have to make sure that the query parameters are indexed at write-time instead of calculating them on the fly.
As an example, if you wanted to do a case-insensitive search by event title, you'd have to store a lower-case copy of the title on every entity at write time. Without guessing your query requirements, I can't really offer more specific advice.
It's possible to run Django on App Engine
You need a trio of apps from here:
http://www.allbuttonspressed.com/projects
Django-nonrel
djangoappengine
djangotoolbox
Additionally, this module makes it possible to do the joins across Foreign Key relationships which are not directly supported by datastore methods:
django-dbindexer
...it denormalises the fields you want to join against, but has some limitations - doesn't update the denormalised values automatically so is only really suitable for static values
Django signals provide a useful starting point for automatic denormalisation.
I defined an expense model for an expense application,
class Expense(models.Model):
pub_date = models.DateTimeField()
amount = models.IntegerField()
memo = models.TextField()
and I would like to create lost of separate tables to maintain data for different users, such as
james_expense_table for james
william_expense_table for william
....
balabala_expense_table for balabala
They are exactly same behavior, like parallel objects. The only difference is the prefix. So that, i can easily extend the application with more features.
So how can I achieve this?
I've read some abstract model stuff from django web. But in fact, they are static, hard coded in the *.py files, not what i want.
And one more question, for a static model (hard code in *.py file), it can use "manage.py syncdb" command to sync the module fields to the table fields, so how can do this for the dynamic case?
What you want is probably to use a ForeignKey so that you can link your table to different users:
class Expense(models.Model):
pub_date = models.DateTimeField()
amount = models.IntegerField()
memo = models.TextField()
user = models.ForeignKey(MyUserField)
Obviously you need to have a MyUserField implemented and imported.
You can then access the user from the Expense table
my_expense.user
Or the Expense table from the user using:
my_user.expense_set.all()
You then don't require to run syncdb for every new user, and it's not statically hard-coded in the file.