How can I set user full name in foreignkey field w

2019-06-16 04:37发布

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.

2条回答
闹够了就滚
2楼-- · 2019-06-16 04:46

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),
    )
查看更多
别忘想泡老子
3楼-- · 2019-06-16 05:03

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.

查看更多
登录 后发表回答