用户必须给硬币提问的问题应用程序,回答者将获得硬币

A question app that the user must give coins to ask a question and the answerer will get the coins

enter code here我正在创建一种问答 Web 应用程序。我想让提问的用户强制给硬币。选择已经存在。然后回答问题的用户得到其他用户给的硬币。我正在使用 Django 信号,但是提出问题的用户扣除了他的硬币,但回答者没有得到任何硬币,这是给我一个错误。这是问答的模型。我已经有了用户默认硬币为 5000 的用户模型

class Question(models.Model):
    COINS_CHOICES = (
        (10, 10),
        (20, 20),
        (30, 30),
        (40, 40),
        (50, 50),
        (60, 60),
        (70, 70),
        (80, 80),
        (90, 90),
        (100, 100),

    )
    label = models.CharField(max_length=5000)
    image = models.ImageField()
    #slug = models.SlugField()
    timestamp = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now_add=True)
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    coins_given = models.PositiveSmallIntegerField(choices=COINS_CHOICES, blank=False, null=True)

    def __str__(self):
        return self.label
    
class Answer(models.Model):
    label = models.CharField(max_length=5000)
    image = models.ImageField()
    timestamp = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    clap = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="answers")
    
    
    def __str__(self):
        return self.label
    
    
    def number_of_clap(self):
        return self.clap.count()
    
    
class Comment(models.Model):
    text = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    answer = models.ForeignKey(Answer, on_delete=models.CASCADE)

@receiver(post_save, sender=Question)    
def subtract_coins_from_user(sender, instance, created, **kwargs):
    if created:
        profile = instance.user
        profile.coin -= instance.coins_given
        profile.save()
        
    
@receiver(post_save, sender=Answer)
def add_coins_to_user(sender, instance, created, **kwargs):
    if created:
        profile = instance.user
        profile.coin += instance.coins_given
        profile.save()
    

一个Answer模型没有字段coins_given,相关问题有,所以你得到instance.questioncoins_given :

@receiver(post_save, sender=Answer)
def add_coins_to_user(sender, instance, created, **kwargs):
    if created:
        profile = instance.user
        profile.coin += <strong>instance.question.coins_given</strong>
        profile.save()

话虽这么说,但我不确定使用信号是个好主意:信号可以被规避,并且可能有不需要的 side-effects 并使 .save() 的行为更难以预测.