How to insert default value in database table when user account is created in Django?

不羁的心 提交于 2019-12-11 08:41:40

问题


I am using postgre database have 10 channel in my database. This is my models with channelId and userId as foreign key:

class Count(models.Model):
    userId = models.ForeignKey(User, on_delete=models.CASCADE)
    channelId = models.ForeignKey(News_Channel, on_delete=models.CASCADE)
    rate = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.channelId.name

    class Meta:
        ordering = ["-id"]

I want when a user account is created then 3 row inserted in the table for all 3 channelId and rate value set to 0. suppsose a user sign up and get userIid 99 then 3 rows inserted in the table as

userId channelId rate
99         1      0
99         2      0
99         3      0

What could be the possible solution.


回答1:


There are 2 possible solutions:

  1. You can use signals. Create a post_save signal for your AUTH_USER_MODEL. It is usually used to execute some logic just after a model’s save() method is called. In that signal function write logic for creating Count for all channels and rate. You can get id for ATUTH_USER_MODEL from post_signal.

    Refer https://docs.djangoproject.com/en/2.2/topics/signals/

  2. Create a logic for registering user for your AUTH_USER_MODEL and after user creation, create Count for all channels and rate.



来源:https://stackoverflow.com/questions/56303797/how-to-insert-default-value-in-database-table-when-user-account-is-created-in-dj

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