Through the on_delete option, Django provides various alternatives for what to do with objects that have a foreign key to an object that is being deleted.
I'm wondering if there is a way I could do something similar, but conditionally. Here's the scenario. I am utilizing Django 1.5's new custom User model and all my users have a ForeignKey to Site. Like so:
class TenantSiteUser(AbstractUser):
site = models.ForeignKey(Site, null=True)
If a site is deleted, then I'd prefer to delete all the non-superusers linked to that site (i.e., KASKADE-like behavoir), since their existence is now meaningless. But if its a superuser, I'd prefer to just set the user's site to null (i.e., SET_NULL) and let them keep existing, since that's probably me or someone I work with and we tend to not want to unintentionally delete ourselves.
Is there something I can override to manually do a check and implement this type of on_delete behavior?
EDIT: Here's the code that ended up working for me, based on #Kevin's answer and some study of how the existing handlers work:
def NULLIFY_SUPERUSERS_ELSE_CASCADE(collector, field, sub_objs, using):
superusers = []
for user in sub_objs:
if user.is_superuser:
sub_objs = list(sub_objs)
sub_objs.remove(user)
superusers.append(user)
CASCADE(collector, field, sub_objs, using)
if len(superusers):
collector.add_field_update(field, None, superusers)
class TenantSiteUser(AbstractUser):
site = models.ForeignKey(Site, null=True, on_delete=NULLIFY_SUPERUSERS_ELSE_CASCADE)
The options Django provides (CASCADE, PROTECT etc.) are all functions - here's where they're defined for 1.5.
I haven't tested it, but it should be possible to write your own NULL_OR_CASCADE function and pass that in as your field's on_delete argument.
Related
I have an Article model that allows admins to publish articles. Each article is assigned to a user that is creating this article.
I want to make sure that all articles will stay untouched even if I delete the author of this particular article. I chose on_delete=models.DO_NOTHING to be sure that nothing except user account will be removed but I am not quite sure that is the most effective way.
class Article(models.Model):
id = models.AutoField(primary_key=True)
author = models.ForeignKey(User, blank=True, null=True, on_delete=models.DO_NOTHING)
title = models.CharField('Title', max_length=70, help_text='max 70 characters')
body = models.TextField('Description')
Question
Should I use another option to use or DO_NOTHING is good enough. Obviously the most important to me is that author's name will be visible in the article after deletion and the article itself cannot be removed.
Best I can say is:
add another field called author_name.
now set the on_delete of your author to models.SET_NULL.
Add a custom save method to add the name of your user to author_name.
Add a property to your model named author_full_name
in this property check if author is not null return user name and last name.
if author is None return author_name.
This way when the article is saved user full name is saved on author_name. and if user is deleted you can use the author_name.
but watch out for the custom save method it might add some issues if you don't check the user and it's deletion.
Edit: Another solution
If you have a custom user model you can a field to your users called is_deleted.
After your users delete their accounts just set this field to True and have the logic in your app to excludes deleted accounts.
this way your users won't be accessible to anyone but you can use them for the articles and foreign keys. (remember to tell your users that account deletion works this way or set a task to remove accounts after a while and set the field that I said above.)
Basically the database table creates record in certain table and stores user info as I can see you are linking article model with user based on User model.
There can be two cases like if you want the article to remain in database even if you delete the author you will get article when the article gets displayed somewhere.
If you do Cascade delete it deletes article record when associated author gets delete.
If you do models.Protect you wont get access to delete article when you user is deleted.
coming to your very models.Do nothings is a bad idea since this would create integrity issues in your database (referencing an object that actually doesn't exist). SQL equivalent: NO ACTION
find more here.
You just need to use CASCADE as below:
on_delete=models.CASCADE
When deleting an object in admin interface, I want to prevent removal of related objects.
class ObjectToDelete(models.Model):
timestamp = models.DateTimeField()
class RelatedObject(models.Model):
otd = models.ForeignKey('app.ObjectToDelete', null=True, blank=True)
Since the ForeignKey in RelatedObject is nullable, I should be able to set it to None instead of deleting the whole object. And this is exactly the behaviour I want to have.
I know that I can create custom delete actions for this admin interface.
And I am also aware that I could make ManyToManyField in ObjectToDelete which would also prevent removal of RelatedObject. But then I wouldn't have the one-to-many relation which I want.
Is there a simple way of achieving this?
Set the on_delete option for your foreign key. If you you want to set the value to None when the related object is deleted, use SET_NULL:
models.ForeignKey('app.ObjectToDelete', on_delete=models.SET_NULL)
These rules apply however you delete an object, whether you do it in the admin panel or working directly with the Model instance. (But it won't take effect if you work directly with the underlying database in SQL.)
Not sure if this is a bug in Django, or it just doesn't support what I'm trying to do (or how i'm doing it).
A snippet of my model:
class UserProfile(models.Model):
user = models.OneToOneField(User, primary_key=True, related_name='profile'
login_hash = models.CharField(max_length=36, blank=True, null=True, default=uuid.uuid4())
...
As you see, i've set the default for login_hash to a call to uuid.uuid4()
works fine... however, multiple calls to the UserProfile (creating new users quickly, even seemingly a few minutes, but i've not an official time) will result in the same login_hash for multiple users.
It appears that django (i'm on 1.7.4) is caching the result of uuid4() for some period of time. not good for what i'm trying to do.
SOLUTION:
that i'm using. I've simply set an 'on insert' trigger on the database, so that when i insert a new record, the database generates the UUID, but only on inserts/new records.
Is there a way to do it within django so that i can keep it database agnostic?
works fine... however, multiple calls to the UserProfile (creating new users quickly, even seemingly a few minutes, but i've not an official time) will result in the same login_hash for multiple users.
As the code is currently written you're calling uuid.uuid4() at the point UserProfile is imported. It'll be called once and the resulting value will be the default for all new creations.
What you instead what to do is pass a callable as the default. Like so: default=uuid.uuid4.
Also, for CharField I'd strongly suggest not allowing NULL values as well as blank values. It's also not clear if you really do want to allow blank values for this field, but let's assume that you do. You should end up with this:
login_hash = models.CharField(max_length=36, blank=True, default=uuid.uuid4)
So I've got a UserProfile in Django that has certain fields that are required by the entire project - birthday, residence, etc. - and it also contains a lot of information that doesn't actually have any importance as far as logic goes - hometown, about me, etc. I'm trying to make my project a bit more flexible and applicable to more situations than my own, and I'd like to make it so that administrators of a project instance can add any fields they like to a UserProfile without having to directly modify the model. That is, I'd like an administrator of a new instance to be able to create new attributes of a user on the fly based on their specific needs. Due to the nature of the ORM, is this possible?
Well a simple solution is to create a new model called UserAttribute that has a key and a value, and link it to the UserProfile. Then you can use it as an inline in the django-admin. This would allow you to add as many new attributes to a UserProfile as you like, all through the admin:
models.py
class UserAttribute(models.Model):
key = models.CharField(max_length=100, help_text="i.e. Age, Name etc")
value = models.TextField(max_length=1000)
profile = models.ForeignKey(UserProfile)
admin.py
class UserAttributeInline(admin.StackedInline):
model = UserAttribute
class UserProfile(admin.ModelAdmin):
inlines = [UserAttibuteInline,]
This would allow an administrator to add a long list of attributes. The limitations are that you cant's do any validation on the input(outside of making sure that it's valid text), you are also limited to attributes that can be described in plain english (i.e. you won't be able to perform much login on them) and you won't really be able to compare attributes between UserProfiles (without a lot of Database hits anyway)
You can store additional data in serialized state. This can save you some DB hits and simplify your database structure a bit. May be the best option if you plan to use the data just for display purposes.
Example implementation (not tested)::
import yaml
from django.db import models
class UserProfile(models.Model):
user = models.OneToOneField('auth.User', related_name='profile')
_additional_info = models.TextField(default="", blank=True)
#property
def additional_info(self):
return yaml.load(self._additional_info)
#additional_info.setter
def additional_info(self, user_info_dict):
self._additional_info = yaml.dump(user_info_dict)
When you assign to profile.additional_info, say, a dictionary, it gets serialized and stored in _additional_info instead (don't forget to save the instance later). And then, when you access additional_info, you get that python dictionary.
I guess, you can also write a custom field to deal with this.
UPDATE (based on your comment):
So it appears that the actual problem here is how to automatically create and validate forms for user profiles. (It remains regardless on whether you go with serialized options or complex data structure.)
And since you can create dynamic forms without much trouble[1], then the main question is how to validate them.
Thinking about it... Administrator will have to specify validators (or field type) for each custom field anyway, right? So you'll need some kind of a configuration option—say,
CUSTOM_PROFILE_FIELDS = (
{
'name': 'user_ip',
'validators': ['django.core.validators.validate_ipv4_address'],
},
)
And then, when you're initializing the form, you define fields with their validators according to this setting.
[1] See also this post by Jacob Kaplan-Moss on dynamic form generation. It doesn't deal with validation, though.
I'm finding conflicting information on whether to use OneToOneField(User) or ForeignKey(User, unique=True) when creating a UserProfile model by extending the Django User model.
Is it better to use this?:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
or this?:
class UserProfile(models.Model):
user = models.OneToOneField(User)
The Django Doc specifies OneToOneField, while the Django Book example uses ForeignKey.
James Bennett also has two Blog posts that providing conflicting examples as well:
Extending the User Model
User Registration
In the former post, Bennett provides some reasons why he switched to using ForeignKey instead of OneToOneField, but I don't quite get it, especially when I see other posts that recommend the opposite.
I'm curious to know your preference and why. Or, does it even matter?
The only real reason given in the article is that it can be set up so that the admin page for User will show both the fields in User and UserProfile. This can be replicated with a OneToOneField with a little elbow grease, so unless you're addicted to showing it in the admin page with no work at the cost of a bit of clarity ("We can create multiple profiles per user?! Oh no, wait, it's set unique.") I'd use OneToOneField.
Besides the admin page inlines, other reason for the ForeignKey solution is that it allows you to use the correct, default DB manager when objects are accessed with a reverse relation. Consider example from this subclasses manager snippet. Let's say that the Post class definition from the example looks like this:
class Post(ParentModel):
title = models.CharField(max_length=50)
onetoone = models.ForeignKey(SomeModel, unique=True)
children = ChildManager()
objects = models.Manager()
By calling somemodel_instance.post_set.all()[0], you get the desired subclasses objects of the Post class as indicated by defining the first (default) manager as a ChildManager. On the other hand, with OneToOneField, by calling somemodel_instance.post you get the Post class instance. You can always call somemodel_instance.post.subclass_object and get the same result, but the default manager could do any other sort of tricks and the FK solutions hides them nicely.
If you own and can modify the custom manager code you can use the use_for_related_fields attribute instead of using FK in place of legitimate 1to1 field, but even that can fail because of some not-known to me nuisances of the automatic managers. As far as I remember it will fail in the above example.
Other reason to generally not use the OneToOneField related to reverse relations: when you use reverse relations defined via OneToOneField you get an model instance, contrary to Manager for ForeignKey reverse relation and as a consequence there's always a DB hit. This is costly if you do some generic stuff on reverse relations (via _meta.get_all_related_objects()) and do not know and care if you will use them all or not.