I'm new to django programming, and trying to get to grips with GenericForeignKeys.
I've managed to create a generic foreign key which stores in the database, but the model does not appear to enforce referential integrity,
(i.e. I can create a reference to an ID of an object type where that object id does not exist)
(eg: content_type: "post", content_id: 123, but post 123 does not exists).
(Before you say it - Yes - I'm aware that Django has some facility for tagging - this is a really simple example/test for me to understand Generic Foreign Keys, and figure out how they work, so I can implement them in other situations)
My basic model is:
class Tag(NamedModel, models.Model):
taggable_models = models.Q(models.Q(model='post') | models.Q(model='discussion'))
content_type = models.ForeignKey(
ContentType,
models.CASCADE,
limit_choices_to=taggable_models,
)
content_id = models.PositiveIntegerField(
_("content id"),
)
content_object = GenericForeignKey(
'content_type',
'content_id',
)
In my admin.py, I have:
@admin.register(Tag)
class TagAdmin(VersionAdmin):
readonly_fields = ('created_at',)
list_display = ('content_type', 'content_id', 'created_at', )
fieldsets = (
(None, {
'fields': ('content_type', 'content_id', 'created_at', ),
}),
)
autocomplete_lookup_fields = {
'generic': [['content_type', 'content_id']],
}
However, when I run the admin page, it will allow me to create a Tag against a post id that does not exist.
Is there some way that I can enforce referential integrity here? I guess I need to use the content_object GenericForeignKey somehow, but I can't figure out how to do this?
Thank kindly for any help,
Christopher.