Generic Foreign Key on unsaved model in Django

I have stumbled into a bit of inconsistency with Foreign Keys and Generic Foreign Keys in Django. Suppose we have three models

class Model_One(models.Model):
    name= models.CharField(max_length=255)

class Model_with_FK(models.Model):
    name=models.CharField(max_length=255)
    one=models.ForeignKey(Model_One, on_delete=models.CASCADE)

class Model_With_GFK(models.Model):
    name=models.CharField(max_length=255)
    content_type= models.ForeignKey(
        ContentType, on_delete=models.CASCADE,
    )
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey("content_type", "object_id")
    class Meta:
        indexes=[models.Index(fields=["content_type", "object_id"]), ]

When we do

one = Model_One()
two = Model_Two(model_one=one)
one.save()
two.save()

Everything works okay. Model one recieves an ID, and when model two is saved, that ID is used to reference model one. However, the same does not work with GFK

one = Model_One()
two = Model_With_GFK(content_object=one)
one.save()
two.save()

When there is an attempt to save two, integrity error is raised that “object_id” column is null. When inspected with debugger, as soon as model one is saved, field “content_object”on the model two is turn from model “one” to None. This is quite unexpected, as with Foreign Key there is no such problem.

Of course you can save model one before using it in GFK relation, but why is this necessary? With Foreign keys, i could instantiate all the models and then create them with bulk_create. With GFK in the picture, this no longer seems possible

New contributor

Gigerin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

Django’s GenericForeignKey has been implemented in a bit more “boring” way. Indeed, it works with the .set(…) descriptor [GitHub]:

def __set__(self, instance, value):
    ct = None
    fk = None
    if value is not None:
        ct = self.get_content_type(obj=value)
        fk = value.pk

    setattr(instance, self.ct_field,ct)
    setattr(instance, self.fk_field, fk)
    self.set_cached_value(instance, value)

It thus does not do that much, besides finding the content_type and the primary key for the value you select, and sets the ct_field (content type), and the fk_field (the field that stores primary keys).

Strictly speaking, it could be done by rewriting the the ._prepare_related_fields_for_save(…) [GitHub] to postpone the saving until you save the object to the database, but this thus has not been done.

N.B.: I opened a ticket [Django-ticket] for this.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật