The Django ORM creates new instances of objects for each db request.
    This is a problem for PyAMF as it uses the C{id(obj)} of the object to do
    reference checking.

    We could just ignore the problem, but the objects are conceptually the
    same so the effort should be made to attempt to resolve references for a
    given object graph.

    We create a new map on the encoder context object which contains a dict of
    C{object.__class__: {key1: object1, key2: object2, .., keyn: objectn}}. We
    use the primary key to do the reference checking.

    @since: 0.5

def writeDjangoObject(obj, encoder=None):
    """
    The Django ORM creates new instances of objects for each db request.
    This is a problem for PyAMF as it uses the C{id(obj)} of the object to do
    reference checking.

    We could just ignore the problem, but the objects are conceptually the
    same so the effort should be made to attempt to resolve references for a
    given object graph.

    We create a new map on the encoder context object which contains a dict of
    C{object.__class__: {key1: object1, key2: object2, .., keyn: objectn}}. We
    use the primary key to do the reference checking.

    @since: 0.5
    """
    s = obj.pk

    if s is None:
        encoder.writeObject(obj)

        return

    django_objects = getDjangoObjects(encoder.context)
    kls = obj.__class__

    try:
        referenced_object = django_objects.getClassKey(kls, s)
    except KeyError:
        referenced_object = obj
        django_objects.addClassKey(kls, s, obj)

    encoder.writeObject(referenced_object)