📅  最后修改于: 2023-12-03 15:14:43.175000             🧑  作者: Mango
Django GenericForeignKey provides a way to create a relation between any two models without explicitly defining a foreign key constraint in the database. It uses content types framework to create a relation between models.
In some cases, you may not want to enforce the foreign key constraint and allow the relation to be null. This can be achieved by setting the null=True
parameter on the GenericForeignKey field.
Let's say we have two models Model_A
and Model_B
:
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Model_A(models.Model):
name = models.CharField(max_length=100)
class Model_B(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
By default, content_object
field would not allow null
values. To allow null values, we can modify Model_B
as follows:
class Model_B(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id', null=True)
In conclusion, if you want to allow the relation between two models to be null, set null=True
parameter on the GenericForeignKey
field. This will allow the field to store None
as a value.