【问题标题】:I have a complicated model issues... more info inside我有一个复杂的模型问题...里面有更多信息
【发布时间】:2012-11-03 15:47:46
【问题描述】:

所以基本上我的应用程序当然有用户,每个用户可以创建 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”实例。

如何在模型逻辑中做到这一点?

谢谢

【问题讨论】:

  • 如果你能分享模型的定义会很有帮助。

标签: python django django-models


【解决方案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()

【讨论】:

  • 我不确定,但会测试一下。
猜你喜欢
  • 1970-01-01
  • 2022-01-10
  • 2018-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多