问题
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:
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/
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