0

I want the a counterpart of Tag (BlogPost) to have at least 1 instance of Tag or it shouldn't be created. (same effect like null=False). I tried a lot but couldn't figure out to apply these contrains. Any ideas?

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,)
j7nn7k
  • 17,995
  • 19
  • 78
  • 88
  • 1
    i just realized, thats not possible to make this contrain, cause both require each other to exist while creating. deadlock. so topic is closed =/ – j7nn7k Oct 11 '12 at 10:43

1 Answers1

0

If you want this in the form of a Database constraint, then I'm not sure that such a thing exists.

Otherwise I would go with overriding the clean( self ) function on your model. This can be used for custom validation.

def clean( self ):
    # validate that this model has one or more tag
A.J.Rouvoet
  • 1,203
  • 1
  • 14
  • 29