0

所以基本上我的应用程序当然有用户,每个用户可以创建 5 个“ModelA”实例。很简单,但也有与“ModelA”和用户模型相关的“ModelB”。我希望用户能够创建总共 15 个“ModelB”实例,但每个“ModelA”实例只能绑定 5 个“ModelB”实例?

有小费吗?

我为每个用户处理 5 个“ModelA”实例的第一部分的方式是这样的:

def clean(self):
        new_instance = self.__class__
        if (new_instance.objects.count() > 4):
            raise ValidationError(
                "Users may only create 5 %s." % new_instance.verbose_name_plural
            )
        super(ModelA, self).clean()

谢谢

编辑:(假设内置 Django 用户功能)

class ModelB(models.Model):
    user = models.ForeignKey(User)
    modelA = models.ForeignKey('ModelA')
    other_field = models.CharField(max_length=50)

class ModelA(models.Model):
    user = models.ForeignKey(User)
    other_field = models.CharField(max_length=50)

基本上,用户可以创建 5 个“ModelA”实例,并且对于每个实例,他们可以创建 3 个“ModelB”实例。

我怎样才能在模型逻辑中做到这一点?

谢谢

4

1 回答 1

1

这行得通吗?

class ModelB(models.Model):
  user = models.ForeignKey(User)
  modelA = models.ForeignKey('ModelA', related_name = 'modelbs')
  other_field = models.CharField(max_length=50)

  def clean(self):
    if (self.modelA.modelbs.all().count() > 2):
        raise ValidationError(
            "ModelA may create may only create 3 modelBs "
        )
    super(ModelB, self).clean()


class ModelA(models.Model):
  user = models.ForeignKey(User, related_name = 'modelas')
  other_field = models.CharField(max_length=50)

  def clean(self):
    if (self.user.modelas.all().count() > 2):
        raise ValidationError(
            "User may create may only create 3 modelAs "
        )
    super(ModelA, self).clean()
于 2012-11-15T03:20:09.310 回答