错误消息:
blogs.Permission: (fields.E336) The model is used as an intermediate model by 'blogs.Category.permission', but it does not have a foreign key to 'Category' or 'Permission'.
我试图在“权限”模型下向“类别”添加外键,仍然会发生相同的错误。
models.py:
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=50)
permission = models.ManyToManyField('Permission',
related_name='category_permissions',
through='Permission'
)
def __str__(self):
return self.name
class Permission(models.Model):
HIGH = 'High'
MEDIUM = 'Medium'
LOW = 'Low'
CLASSIFICATION_CHOICES = [
(HIGH, 'High'),
(MEDIUM, 'Medium'),
(LOW, 'Low')
]
category_name = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_name')
name = models.CharField(max_length=100)
description = models.TextField()
platform = models.CharField(
max_length=10,
choices=PLATFORM_CHOICES,
default=BOTH,
)
classification = models.CharField(
max_length=10,
choices=CLASSIFICATION_CHOICES,
default=LOW,
)
def __str__(self):
return self.name
class MobileApp(models.Model):
name = models.CharField(max_length=200)
icon = models.ImageField(upload_to='app_icons', blank=True, null=True)
platform = models.CharField(
max_length=10,
choices=PLATFORM_CHOICES,
default=IOS,
)
category = models.ManyToManyField('Category')
provider = models.CharField(max_length=200)
identifier = models.CharField(max_length=200)
permission = models.ManyToManyField(Permission,
related_name='mobile_app_permission',
)
def __str__(self):
return self.name
我正在尝试使用'through'参数来包括对MobileApp和Category的权限m2m的描述字段
答案 0 :(得分:0)
这很糟糕。
显然,您希望多对多介于Category和MobileApp之间,直通模型为Permission。因此,m2m字段需要声明:
val size = someOtherObject.subObjects().size
val s = size match {
case size > 0 => "Size is greater than 0"
case _ => "Size is less than 0"
}
第二,作为错误状态,在直通模型中,您都需要双方的外键。另外,您需要给他们提供明智的名称和related_names。所以:
class Category(models.Model):
name = models.CharField(max_length=50)
permission = models.ManyToManyField('MobileApp',
related_name='category_permissions',
through='Permission'
)
最后,您不需要还需要在另一个方向上将m2ms定义为权限或类别。从MobileApp中删除class Permission(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='permissions')
mobile_app = models.ForeignKey('MobileApp', on_delete=models.CASCADE, related_name='permissions')
和category
字段。