自动生成在Django
问题描述:
上创建实例表中的连接在下面的简单的系统,其中用户可以收集任何数量的任何类型的徽章的:自动生成在Django
__________ _____________ _______
| User | | BadgeDone | | Badge |
| -------- | <------ | ----------- | ------> | ----- |
| username | | count = 0 | | name |
|__________| | FK user_id | |_______|
| FK badge_id |
|_____________|
models.py:
class BadgeDone(models.Model):
count = models.IntegerField(default = 0)
user = models.ForeignKey(
'auth.User',
on_delete = models.CASCADE,
)
badge = models.ForeignKey(
'Badge',
on_delete = models.CASCADE,
)
def __str__(self):
return self.user.username + '_' + self.badge.name
class Badge(models.Model):
name = models.CharField(max_length = 50)
def __str__(self):
return self.name
我试图自动创建新创建的用户和每个现有的徽章之间的连接,反之亦然(即在新创建的徽章和每个现有用户之间)。
,得到期望的行为的一个例子:
Badges.objects.all()
<QuerySet [<Badge: Bronze>, <Badge: Silver>, <Badge: Gold>]>
BadgesDone.objects.all()
<QuerySet []>
User.object.all()
<QuerySet []>
u = User(username='John')
u.save()
Badges.objects.all()
<QuerySet [<Badge: Bronze>, <Badge: Silver>, <Badge: Gold>]>
BadgesDone.objects.all()
<QuerySet [<BadgeDone: John_Bronze>, <BadgeDone: John_Silver>, <BadgeDone: John_Gold>]>
User.object.all()
<QuerySet [User: John]>
b = Badge(name='BlackGold')
b.save()
Badges.objects.all()
<QuerySet [<Badge: Bronze>, <Badge: Silver>, <Badge: Gold>, <Badge: BlackGold>]>
BadgesDone.objects.all()
<QuerySet [<BadgeDone: John_Bronze>, <BadgeDone: John_Silver>, <BadgeDone: John_Gold>, <BadgeDone: John_BlackGold>]>
User.object.all()
<QuerySet [User: John]>
目前我使用的扫描丢失的连接,并生成这些外部脚本,但这只是为快速概念性测试OK,所以我的问题。 在确保松散耦合的保留的同时,在Django中实现这一点的正确方法是什么?
答
你可以尝试Django的post-save信号
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User, dispatch_uid="user_badges_add")
def badges_add(sender, instance, created, **kwargs):
if created:
for badge in Badges.objects.all():
BadgesDone.objects.create(user=instance, badge=badge)
+0
谢谢,只是测试它,它确实是我所需要的。 – Lukas
你说的是'makemigrations'? –