问题描述
我正在使用postgre数据库,数据库中有10个通道。这是我的使用channelId和userId作为外键的模型:
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"]
我想要在创建用户帐户时将表中的3行插入,并将所有3个channelId和费率值设置为0。
支持用户注册并获得userIid 99,然后将3行插入表中
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
可能是什么解决方案
推荐答案
有2种可能的解决方案:
There are 2 possible solutions:
-
您可以使用信号s。为您的AUTH_USER_MODEL创建一个post_save信号。通常用于在调用模型的save()方法之后执行一些逻辑。在该信号功能中,编写用于为所有通道和速率创建计数的逻辑。您可以从post_signal中获取ATUTH_USER_MODEL的ID。
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.
引用
创建逻辑为您的AUTH_USER_MODEL注册用户,并在创建用户后,为所有频道和费率创建计数。
Create a logic for registering user for your AUTH_USER_MODEL and after user creation, create Count for all channels and rate.
这篇关于在Django中创建用户帐户时,如何在数据库表中插入默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!