【问题标题】:Generic Relation Constraints in DjangoDjango 中的通用关系约束
【发布时间】:2012-10-10 15:19:01
【问题描述】:

我希望 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,)

【问题讨论】:

  • 我刚刚意识到,这不可能使这个约束,因为在创建时两者都需要彼此存在。僵局。所以主题关闭了=/

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


【解决方案1】:

如果您希望以数据库约束的形式进行此操作,那么我不确定是否存在这样的事情。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 2019-09-29
    • 2012-08-08
    • 1970-01-01
    • 2020-03-17
    • 2017-04-12
    相关资源
    最近更新 更多