Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 526
Neeraj Kumar Avatar asked Mar 06 '17 17:03

Neeraj Kumar


People also ask

What does Django DB models model ForeignKey On_delete protect do?

The PROTECT argument of the ForeignKey on_delete option prevents the referenced object from being deleted if it already has an object referencing it in the database. Put simply, Django will prevent a post from deletion if it already has comments.

What is On_delete models Set_null?

simply put, on_delete is an instruction to specify what modifications will be made to the object in case the foreign object is deleted: CASCADE: will remove the child object when the foreign object is deleted. SET_NULL: will set the child object foreign key to null.

How do you add an extra field in user model?

In the ready-made model structure that comes in the Django Framework, if new fields are needed in the User model, we can solve it in two ways. One of them is extending the AbstractBaseUser model. The second is to create a new model and connect it to the User model with a one-to-one relationship.


1 Answers

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.

like image 53
narendra-choudhary Avatar answered Nov 01 '22 01:11

narendra-choudhary