Ticket #13137: allow_contenttype_pk_0_with_tests.diff

File allow_contenttype_pk_0_with_tests.diff, 2.6 KB (added by devesine, 5 years ago)

Proposed patch (with tests)

  • django/contrib/contenttypes/generic.py

     
    5151        ContentType = get_model("contenttypes", "contenttype")
    5252        if obj:
    5353             return ContentType.objects.db_manager(obj._state.db).get_for_model(obj)
    54         elif id:
     54        elif id is not None:
    5555             return ContentType.objects.db_manager(using).get_for_id(id)
    5656        else:
    5757            # This should never happen. I love comments like this, don't you?
     
    7272            # performance when dealing with GFKs in loops and such.
    7373            f = self.model._meta.get_field(self.ct_field)
    7474            ct_id = getattr(instance, f.get_attname(), None)
    75             if ct_id:
     75            if ct_id is not None:
    7676                ct = self.get_content_type(id=ct_id, using=instance._state.db)
    7777                try:
    7878                    rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field))
  • tests/modeltests/generic_relations/models.py

     
    7878    def __unicode__(self):
    7979        return self.name
    8080
     81class ContentZero(models.Model):
     82    name = models.CharField(max_length=50)
     83   
    8184__test__ = {'API_TESTS':"""
    8285# Create the world in 7 lines of code...
    8386>>> lion = Animal(common_name="Lion", latin_name="Panthera leo")
     
    214217>>> valuedtag.content_object
    215218<Mineral: Quartz>
    216219
     220# GenericForeignKey should work with ContentType ID 0 (see #13137)
     221# Update ContentZero to be content type ID 0...
     222>>> from django.contrib.contenttypes.models import ContentType
     223>>> ContentType.objects.filter(app_label='generic_relations', model='contentzero').update(id=0)
     2241
     225>>> ContentType.objects.clear_cache()
     226>>> zerotype = ContentType.objects.get_for_model(ContentZero)
     227>>> zerotype.id
     2280
     229
     230>>> objectzero = ContentZero(name="zero")
     231>>> objectzero.save()
     232>>> tagzero = TaggedItem(tag="zero tag", content_object=objectzero)
     233>>> tagzero.save()
     234>>> fetchtag = TaggedItem.objects.get(id=tagzero.id)
     235>>> fetchtag.content_object is not None
     236True
     237>>> fetchtag.content_object == objectzero
     238True
     239
     240# Make sure we can get there through a generic relationship...
     241
     242
    217243# GenericInlineFormSet tests ##################################################
    218244
    219245>>> from django.contrib.contenttypes.generic import generic_inlineformset_factory
Back to Top