In my database I want to synchronize two tables. I use auth_user(Default table provided by Django) table for registration and there was another table user-profile that contain entities username, email, age etc. How to autometically upadate the columns username and email in user-profile according to updation in auth_user table.
from django.contrib.auth.models import User
class profile(models.Model):
username = models.CharField(max_length = 30)
email = models.EmailField()
age = models.PositiveIntegerField()
auth_user_id = models.ForeignKey(User)
You can either modify the django registration code and include the code to save into your profile model on every new registration.
Or
You can set a signal on every save of User model. See the documentation.
def create_profile(sender, **kwargs):
if kwargs["created"]:
p = Profile(user=kwargs["instance"], ...)
p.save()
django.db.models.signals.post_save.connect(create_profile, sender=User)
create_profile() will be called every time any User object is saved.
In this example, I create Profile object only if a new User instance has been created. You can modify it to change existing Profile objects on every change in User instance, also.
Related
In my Appengine (using ndb) application I store users and both username and email need to be unique.
I also need to be able to update progress (save level if higher than previously stored level), change email and pw and delete account.
I noticed that it is not possible to query without ancestors in a transaction. But creating an ancestor is NOT a solution since that would limit the number of writes to 1 per second which is not OK if the app gets popular. So I need another solution.
Is it possible to use the Key? Yes, but that only makes the username unique, how can I make sure noone is reusing the email for another account?
You should be able to use a cross group transaction for this along with an entity that exists solely for reserving email addresses.
For your User entity, you could use the username as the key name. When creating a user, you also create an EmailReservation entity that has the user's email address as a key name.
You then use a cross-group transaction to create a new user:
#ndb.transactional(xg=True)
def create_user(user_name, email):
user = User.get_by_id(user_name)
email_reservation = EmailReservation.get_by_id(email)
if user or email_reservation:
# Either the user_name or email is already in use so stop
return None
# Create the user and reserve the email address so others can't use it
user = User(id=user_name)
email_reservation = EmailReservation(id=email)
ndb.put_multi(user, email_reservation)
return user
I have userdetails table and user table where user has many userdetails ,& userdetails belongs to user.
on userdetails/add i want the cost column under user table to be saved on userdetails/add->submit.
in my userdetails/add form i have $this->Userdetail->input(User.cost);
in my controller userdetails -> add i am using saveall .
now when i add a new user detail ,a user detail record is created and in user table a new record is created with cost column filled what i entered in userdetail add form,
what i want is cost in user column should not be added as a new record,it should be saved or updated with the user i have logged in .
i want to know how to pass condition in saveall so that when i add a user detail the cost column in user is saved but in front of the logged in user not a newly created record in user.
What you need to do is set the User ID to the ID of the logged in user, before saving. If the ID isn't set it creates a new record, so to edit an existing record it has to be set.
Try this before saving:
$this->User->id = $this->Auth->user('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.
Suppose I have an entity class that stores a username:
class Profile {
private String userName;
...
}
Then in the database I have two tables:
--- USERS ---
-> username (varchar)
-> uid (int)
--- PROFILES ---
-> uid
There is a one to one relationship between the USERS and PROFILES tables joining on uid. I want my Profile entity class to have all the fields of the PROFILES table but swap out the uid for the username in the class instead. I just want to use the uid for joins and to conserve space in the database. Note I am using Spring's HibernateTemplate() to execute the named queries I created.
Is there a way I can use JPA to map the userName field of another table into the Profiles entity? When I save a Profile entity, how will it know it was just a joined field?
I believe you can do this with a #SecondaryTable annotation.
I think you'll have to have the uid in a field in the entity class, but i imagine that won't be a problem.
I have a table of Users who are permissioned to edit one of a collection of other tables (each which has a last_modified field to indicate the last time it was changed). I have another table that tracks each change as it is made (I have a better way to track history/versioning, but this is meant more for posting a rolling list of updates to the user)
class WhatsNew(models.Model):
author = models.ForeignKey(User)
model_update = models.CharField("Database Table", max_length=100)
object_id = models.IntegerField("Object ID")
object_name = models.CharField("Object Name", max_length=100)
changed = models.TextField("Fields Updated", blank=True, null=True)
pub_date = models.DateTimeField("Date/Time of Update", auto_now_add=True)
I want the user to be able to see all of the edits they have made. I would do this by querying the above table, filtering on the author. But in addition, I want the user to see a list of the edits they made grouped by id. So for instance, if user 12345 edited object 2-1, then 3-2, then 2-1 again, then 4-4, I want the user to be able to see the a list (2-1, 3-2, 4-4), the time they modified the object, and the time the object was modified by anyone.
Should I capture all of this data in a separate table or try to query it from the WhatsNew table? I think I should capture it in a new table to avoid a possibly expensive query, but I don't want to duplicate information that is already availble in the database.