How can I set user full name in foreignkey field with User Model using on_delete attribute?

纵饮孤独 提交于 2019-12-08 15:58:31

问题


I have a model in django that have foreignkey with User model.

class News(models.Model):
    user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.SET(???))
    message - models.TextField()

So When any user account delete from database then in News table entries also deleted according to user. So I want that When any user account deleted then I need to set his/her full name in user field using 'on_delete=models.SET(???)'

Example:

If I have user that first_name = 'Neeraj' and last_name='Kumar' When I want to delete that user account then in News table I want to save his name.


回答1:


user field in News Model maps to a User Model instance.

You cannot assign a string to this field. You can only assign either null a User model instance.

You will have to provide a substitute user to put in place of the deleted user. So either reserve a user for substitution or create one at the time of deletion. It is explained very clearly in the docs.

One thing you can do is to add a new name field to the News model and populate it when creating the News instance.

class News(models.Mode):
    user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.SET_NULL)
    name = models.CharField()

    def save(self, *args, **kwargs):
        if not self.id:
            self.name = self.user.first_name + self.user.last_name
        super(News, self).save(*args, **kwargs)

Now when User is deleted, user field is set to NULL and name field contains the required name information.




回答2:


As in the previous answer, you cannot assign string value into ForeignKey field. With this on_delete approach, you can assign a special user something like deleted in this case. Furthermore, if you really want to assign user's name into another field, you can do it with Django signal. There is nothing can do about with on_delete.

from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models

def get_sentinel_user():
    return get_user_model().objects.get_or_create(username='deleted')[0]

class MyModel(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET(get_sentinel_user),
    )


来源:https://stackoverflow.com/questions/42632464/how-can-i-set-user-full-name-in-foreignkey-field-with-user-model-using-on-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!