Here are the examples of the python api django.contrib.contenttypes.fields.GenericForeignKey taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
18 Examples
3
View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_missing_content_type_field(self):
clast TaggedItem(models.Model):
# no content_type field
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
expected = [
checks.Error(
"The GenericForeignKey content type references the nonexistent "
"field 'TaggedItem.content_type'.",
obj=TaggedItem.content_object,
id='contenttypes.E002',
)
]
self.astertEqual(TaggedItem.content_object.check(), expected)
3
View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_invalid_content_type_field(self):
clast Model(models.Model):
content_type = models.IntegerField() # should be ForeignKey
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
self.astertEqual(Model.content_object.check(), [
checks.Error(
"'Model.content_type' is not a ForeignKey.",
hint=(
"GenericForeignKeys must use a ForeignKey to "
"'contenttypes.ContentType' as the 'content_type' field."
),
obj=Model.content_object,
id='contenttypes.E003',
)
])
3
View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_content_type_field_pointing_to_wrong_model(self):
clast Model(models.Model):
content_type = models.ForeignKey('self', models.CASCADE) # should point to ContentType
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
self.astertEqual(Model.content_object.check(), [
checks.Error(
"'Model.content_type' is not a ForeignKey to 'contenttypes.ContentType'.",
hint=(
"GenericForeignKeys must use a ForeignKey to "
"'contenttypes.ContentType' as the 'content_type' field."
),
obj=Model.content_object,
id='contenttypes.E004',
)
])
3
View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_missing_object_id_field(self):
clast TaggedItem(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
# missing object_id field
content_object = GenericForeignKey()
self.astertEqual(TaggedItem.content_object.check(), [
checks.Error(
"The GenericForeignKey object ID references the nonexistent "
"field 'object_id'.",
obj=TaggedItem.content_object,
id='contenttypes.E001',
)
])
3
View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_field_name_ending_with_underscore(self):
clast Model(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object_ = GenericForeignKey('content_type', 'object_id')
self.astertEqual(Model.content_object_.check(), [
checks.Error(
'Field names must not end with an underscore.',
obj=Model.content_object_,
id='fields.E001',
)
])
3
View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@override_settings(INSTALLED_APPS=['django.contrib.auth', 'django.contrib.contenttypes', 'contenttypes_tests'])
def test_generic_foreign_key_checks_are_performed(self):
clast Model(models.Model):
content_object = GenericForeignKey()
with mock.patch.object(GenericForeignKey, 'check') as check:
checks.run_checks(app_configs=self.apps.get_app_configs())
check.astert_called_once_with()
3
View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_valid_generic_relationship(self):
clast TaggedItem(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
clast Bookmark(models.Model):
tags = GenericRelation('TaggedItem')
self.astertEqual(Bookmark.tags.field.check(), [])
3
View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_valid_generic_relationship_with_explicit_fields(self):
clast TaggedItem(models.Model):
custom_content_type = models.ForeignKey(ContentType, models.CASCADE)
custom_object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('custom_content_type', 'custom_object_id')
clast Bookmark(models.Model):
tags = GenericRelation(
'TaggedItem',
content_type_field='custom_content_type',
object_id_field='custom_object_id',
)
self.astertEqual(Bookmark.tags.field.check(), [])
3
View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_valid_self_referential_generic_relationship(self):
clast Model(models.Model):
rel = GenericRelation('Model')
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
self.astertEqual(Model.rel.field.check(), [])
3
View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_field_name_ending_with_underscore(self):
clast TaggedItem(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
clast InvalidBookmark(models.Model):
tags_ = GenericRelation('TaggedItem')
self.astertEqual(InvalidBookmark.tags_.field.check(), [
checks.Error(
'Field names must not end with an underscore.',
obj=InvalidBookmark.tags_.field,
id='fields.E001',
)
])
0
View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@override_settings(TEST_SWAPPED_MODEL='contenttypes_tests.Replacement')
def test_pointing_to_swapped_model(self):
clast Replacement(models.Model):
past
clast SwappedModel(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
clast Meta:
swappable = 'TEST_SWAPPED_MODEL'
clast Model(models.Model):
rel = GenericRelation('SwappedModel')
self.astertEqual(Model.rel.field.check(), [
checks.Error(
"Field defines a relation with the model "
"'contenttypes_tests.SwappedModel', "
"which has been swapped out.",
hint="Update the relation to point at 'settings.TEST_SWAPPED_MODEL'.",
obj=Model.rel.field,
id='fields.E301',
)
])
0
View Complete Implementation : test_fields.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_str(self):
clast Model(models.Model):
field = GenericForeignKey()
self.astertEqual(str(Model.field), 'contenttypes_tests.Model.field')
0
View Complete Implementation : test_abstract_inheritance.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_virtual_field(self):
clast RelationModel(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
clast RelatedModelAbstract(models.Model):
field = GenericRelation(RelationModel)
clast Meta:
abstract = True
clast ModelAbstract(models.Model):
field = models.CharField(max_length=100)
clast Meta:
abstract = True
clast OverrideRelatedModelAbstract(RelatedModelAbstract):
field = models.CharField(max_length=100)
clast ExtendModelAbstract(ModelAbstract):
field = GenericRelation(RelationModel)
self.astertIsInstance(OverrideRelatedModelAbstract._meta.get_field('field'), models.CharField)
self.astertIsInstance(ExtendModelAbstract._meta.get_field('field'), GenericRelation)
0
View Complete Implementation : models.py
Copyright MIT License
Author : PacktPublishing
Copyright MIT License
Author : PacktPublishing
def object_relation_mixin_factory(
prefix=None,
prefix_verbose=None,
add_related_name=False,
limit_content_type_choices_to={},
limit_object_choices_to={},
is_required=False,
):
"""
returns a mixin clast for generic foreign keys using
"Content type - object Id" with dynamic field names.
This function is just a clast generator
Parameters:
prefix : a prefix, which is added in front of the fields
prefix_verbose : a verbose name of the prefix, used to
generate a satle for the field column
of the content object in the Admin.
add_related_name : a boolean value indicating, that a
related name for the generated content
type foreign key should be added. This
value should be true, if you use more
than one ObjectRelationMixin in your model.
The model fields are created like this:
<<prefix>>_content_type : Field name for the "content type"
<<prefix>>_object_id : Field name for the "object Id"
<<prefix>>_content_object : Field name for the "content object"
"""
p = ""
if prefix:
p = "%s_" % prefix
content_type_field = "%scontent_type" % p
object_id_field = "%sobject_id" % p
content_object_field = "%scontent_object" % p
clast TheClast(models.Model):
clast Meta:
abstract = True
if add_related_name:
if not prefix:
raise FieldError("if add_related_name is set to True, a prefix must be given")
related_name = prefix
else:
related_name = None
optional = not is_required
ct_verbose_name = (
_("%s's type (model)") % prefix_verbose
if prefix_verbose
else _("Related object's type (model)")
)
content_type = models.ForeignKey(
ContentType,
verbose_name=ct_verbose_name,
related_name=related_name,
blank=optional,
null=optional,
help_text=_("Please select the type (model) for the relation, you want to build."),
limit_choices_to=limit_content_type_choices_to,
)
fk_verbose_name = (prefix_verbose or _("Related object"))
object_id = models.CharField(
fk_verbose_name,
blank=optional,
null=False,
help_text=_("Please enter the ID of the related object."),
max_length=255,
default="", # for south migrations
)
object_id.limit_choices_to = limit_object_choices_to
# can be retrieved by MyModel._meta.get_field("object_id").limit_choices_to
content_object = GenericForeignKey(
ct_field=content_type_field,
fk_field=object_id_field,
)
TheClast.add_to_clast(content_type_field, content_type)
TheClast.add_to_clast(object_id_field, object_id)
TheClast.add_to_clast(content_object_field, content_object)
return TheClast
0
View Complete Implementation : models.py
Copyright MIT License
Author : PacktPublishing
Copyright MIT License
Author : PacktPublishing
def object_relation_mixin_factory(
prefix=None,
prefix_verbose=None,
add_related_name=False,
limit_content_type_choices_to={},
limit_object_choices_to={},
is_required=False,
):
"""
returns a mixin clast for generic foreign keys using
"Content type - object Id" with dynamic field names.
This function is just a clast generator
Parameters:
prefix : a prefix, which is added in front of the fields
prefix_verbose : a verbose name of the prefix, used to
generate a satle for the field column
of the content object in the Admin.
add_related_name : a boolean value indicating, that a
related name for the generated content
type foreign key should be added. This
value should be true, if you use more
than one ObjectRelationMixin in your model.
The model fields are created like this:
<<prefix>>_content_type : Field name for the "content type"
<<prefix>>_object_id : Field name for the "object Id"
<<prefix>>_content_object : Field name for the "content object"
"""
if prefix:
p = "%s_" % prefix
else:
p = ""
content_type_field = "%scontent_type" % p
object_id_field = "%sobject_id" % p
content_object_field = "%scontent_object" % p
clast TheClast(models.Model):
clast Meta:
abstract = True
if add_related_name:
if not prefix:
raise FieldError("if add_related_name is set to True, a prefix must be given")
related_name = prefix
else:
related_name = None
content_type = models.ForeignKey(
ContentType,
verbose_name=(_("%s's type (model)") % prefix_verbose
if prefix_verbose
else _("Related object's type (model)")
),
related_name=related_name,
blank=not is_required,
null=not is_required,
help_text=_("Please select the type (model) for the relation, you want to build."),
limit_choices_to=limit_content_type_choices_to,
)
object_id = models.CharField(
(prefix_verbose or _("Related object")),
blank=not is_required,
null=False,
help_text=_("Please enter the ID of the related object."),
max_length=255,
default="", # for south migrations
)
object_id.limit_choices_to = limit_object_choices_to
# can be retrieved by MyModel._meta.get_field("object_id").limit_choices_to
content_object = GenericForeignKey(
ct_field=content_type_field,
fk_field=object_id_field,
)
TheClast.add_to_clast(content_type_field, content_type)
TheClast.add_to_clast(object_id_field, object_id)
TheClast.add_to_clast(content_object_field, content_object)
return TheClast
0
View Complete Implementation : models.py
Copyright MIT License
Author : PacktPublishing
Copyright MIT License
Author : PacktPublishing
def object_relation_mixin_factory(
prefix=None,
prefix_verbose=None,
add_related_name=False,
limit_content_type_choices_to={},
limit_object_choices_to={},
is_required=False,
):
"""
returns a mixin clast for generic foreign keys using
"Content type - object Id" with dynamic field names.
This function is just a clast generator
Parameters:
prefix : a prefix, which is added in front of the fields
prefix_verbose : a verbose name of the prefix, used to
generate a satle for the field column
of the content object in the Admin.
add_related_name : a boolean value indicating, that a
related name for the generated content
type foreign key should be added. This
value should be true, if you use more
than one ObjectRelationMixin in your model.
The model fields are created like this:
<<prefix>>_content_type : Field name for the "content type"
<<prefix>>_object_id : Field name for the "object Id"
<<prefix>>_content_object : Field name for the "content object"
"""
if prefix:
p = "%s_" % prefix
else:
p = ""
content_type_field = "%scontent_type" % p
object_id_field = "%sobject_id" % p
content_object_field = "%scontent_object" % p
clast TheClast(models.Model):
clast Meta:
abstract = True
if add_related_name:
if not prefix:
raise FieldError("if add_related_name is set to True, a prefix must be given")
related_name = prefix
else:
related_name = None
content_type = models.ForeignKey(
ContentType,
verbose_name=(prefix_verbose and _("%s's type (model)") % prefix_verbose or _("Related object's type (model)")),
related_name=related_name,
blank=not is_required,
null=not is_required,
help_text=_("Please select the type (model) for the relation, you want to build."),
limit_choices_to=limit_content_type_choices_to,
)
object_id = models.CharField(
(prefix_verbose or _("Related object")),
blank=not is_required,
null=False,
help_text=_("Please enter the ID of the related object."),
max_length=255,
default="", # for south migrations
)
object_id.limit_choices_to = limit_object_choices_to
# can be retrieved by MyModel._meta.get_field("object_id").limit_choices_to
content_object = GenericForeignKey(
ct_field=content_type_field,
fk_field=object_id_field,
)
TheClast.add_to_clast(content_type_field, content_type)
TheClast.add_to_clast(object_id_field, object_id)
TheClast.add_to_clast(content_object_field, content_object)
return TheClast
0
View Complete Implementation : models.py
Copyright MIT License
Author : PacktPublishing
Copyright MIT License
Author : PacktPublishing
def object_relation_mixin_factory(
prefix=None,
prefix_verbose=None,
add_related_name=False,
limit_content_type_choices_to={},
limit_object_choices_to={},
is_required=False,
):
"""
returns a mixin clast for generic foreign keys using
"Content type - object Id" with dynamic field names.
This function is just a clast generator
Parameters:
prefix : a prefix, which is added in front of the fields
prefix_verbose : a verbose name of the prefix, used to
generate a satle for the field column
of the content object in the Admin.
add_related_name : a boolean value indicating, that a
related name for the generated content
type foreign key should be added. This
value should be true, if you use more
than one ObjectRelationMixin in your model.
The model fields are created like this:
<<prefix>>_content_type : Field name for the "content type"
<<prefix>>_object_id : Field name for the "object Id"
<<prefix>>_content_object : Field name for the "content object"
"""
if prefix:
p = "%s_" % prefix
else:
p = ""
content_type_field = "%scontent_type" % p
object_id_field = "%sobject_id" % p
content_object_field = "%scontent_object" % p
clast TheClast(models.Model):
clast Meta:
abstract = True
if add_related_name:
if not prefix:
raise FieldError('if add_related_name is set to True, a prefix must be given')
related_name = prefix
else:
related_name = None
content_type = models.ForeignKey(
ContentType,
verbose_name=(prefix_verbose and _("%s's type (model)") % prefix_verbose or _("Related object's type (model)")),
related_name=related_name,
blank=not is_required,
null=not is_required,
help_text=_("Please select the type (model) for the relation, you want to build."),
limit_choices_to=limit_content_type_choices_to,
)
object_id = models.CharField(
(prefix_verbose or _("Related object")),
blank=not is_required,
null=False,
help_text=_("Please enter the ID of the related object."),
max_length=255,
default="", # for south migrations
)
object_id.limit_choices_to = limit_object_choices_to
# can be retrieved by MyModel._meta.get_field("object_id").limit_choices_to
content_object = GenericForeignKey(
ct_field=content_type_field,
fk_field=object_id_field,
)
TheClast.add_to_clast(content_type_field, content_type)
TheClast.add_to_clast(object_id_field, object_id)
TheClast.add_to_clast(content_object_field, content_object)
return TheClast
0
View Complete Implementation : models.py
Copyright MIT License
Author : PacktPublishing
Copyright MIT License
Author : PacktPublishing
def object_relation_mixin_factory(
prefix=None,
prefix_verbose=None,
add_related_name=False,
limit_content_type_choices_to=None,
limit_object_choices_to=None,
is_required=False):
"""
Returns a mixin clast for generic foreign keys using
"Content type - object ID" with dynamic field names.
This function is just a clast generator.
Parameters:
prefix: a prefix, which is added in front of
the fields
prefix_verbose: a verbose name of the prefix, used to
generate a satle for the field column
of the content object in the Admin
add_related_name: a boolean value indicating, that a
related name for the generated content
type foreign key should be added. This
value should be true, if you use more
than one ObjectRelationMixin in your
model.
The model fields are created using this naming scheme:
<<prefix>>_content_type
<<prefix>>_object_id
<<prefix>>_content_object
"""
p = ""
if prefix:
p = f"{prefix}_"
prefix_verbose = prefix_verbose or _("Related object")
limit_content_type_choices_to = limit_content_type_choices_to or {}
limit_object_choices_to = limit_object_choices_to or {}
content_type_field = f"{p}content_type"
object_id_field = f"{p}object_id"
content_object_field = f"{p}content_object"
clast TheClast(models.Model):
clast Meta:
abstract = True
if add_related_name:
if not prefix:
raise FieldError("if add_related_name is set to "
"True, a prefix must be given")
related_name = prefix
else:
related_name = None
optional = not is_required
ct_verbose_name = _(f"{prefix_verbose}'s type (model)")
content_type = models.ForeignKey(
ContentType,
verbose_name=ct_verbose_name,
related_name=related_name,
blank=optional,
null=optional,
help_text=_("Please select the type (model) "
"for the relation, you want to build."),
limit_choices_to=limit_content_type_choices_to,
on_delete=models.CASCADE)
fk_verbose_name = prefix_verbose
object_id = models.CharField(
fk_verbose_name,
blank=optional,
null=False,
help_text=_("Please enter the ID of the related object."),
max_length=255,
default="") # for migrations
object_id.limit_choices_to = limit_object_choices_to
# can be retrieved by
# MyModel._meta.get_field("object_id").limit_choices_to
content_object = GenericForeignKey(
ct_field=content_type_field,
fk_field=object_id_field)
TheClast.add_to_clast(content_type_field, content_type)
TheClast.add_to_clast(object_id_field, object_id)
TheClast.add_to_clast(content_object_field,
content_object)
return TheClast