Django中的通用关系约束

时间:2012-10-10 15:19:02

标签: django generics django-models django-queryset relationships

我希望Tag(BlogPost)的副本至少有1个Tag实例,或者不应该创建它。 (相同的效果,如null = False)。我尝试了很多,但无法弄清楚应用这些禁忌。有什么想法吗?

class Tag(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    text = models.CharField("text", max_length=255)

    class Meta:
        unique_together = ('content_type', 'object_id', 'text',)


class BlogPost(models.Model):
    title = models.CharField("title", max_length=255)
    tags = generic.GenericRelation(Tag, verbose_name="tags")


class TagInline(generic.GenericTabularInline):
    model = Tag
    extra = 1


class BlogPostAdmin(admin.ModelAdmin):
    inlines = (TagInline,)

1 个答案:

答案 0 :(得分:0)

如果您希望以数据库约束的形式使用它,那么我不确定是否存在这样的事情。

否则我会覆盖您模型上的clean( self ) function。 这可以用于自定义验证。

def clean( self ):
    # validate that this model has one or more tag