I've been reading lately about the generic relations. I know that GenericForeignKey
is to define and manaeg the generic relation using ForeignKey
and PositiveIntegerField
fields. I dove into the source code in search for the __set__
method of the GenericForeignKey
to see how does it work.
Here is the snippet for GenericForeignKey.__set__()
:
def __set__(self, instance, value):
ct = None
fk = None
if value is not None:
ct = self.get_content_type(obj=value)
fk = value._get_pk_val()
setattr(instance, self.ct_field, ct)
setattr(instance, self.fk_field, fk)
setattr(instance, self.cache_attr, value)
and model definition from django docs example:
class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
Question:
When I assign value of guido
to the content_object
then what is the value of each of these paremeters: self
, instance
and value
in the GenericForeignKey.__set__()
?
Is self=<GenericForeignKey: 1>
, instance='content_object'
, and value=<User: guido>
?
>>> guido = User.objects.get(username='Guido')
>>> t = TaggedItem(content_object=guido, tag='bdfl')
>>> t.save()