【发布时间】: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