'Ensure references don\'t cause extra fetches when saving'

def test_query_count_when_saving(self):

    class Organization(Document, ):
        name = StringField()
    class User(Document, ):
        name = StringField()
        orgs = ListField(ReferenceField('Organization'))
    class Feed(Document, ):
        name = StringField()
    class UserSubscription(Document, ):
        name = StringField()
        user = ReferenceField(User)
        feed = ReferenceField(Feed)
    Organization.drop_collection()
    User.drop_collection()
    Feed.drop_collection()
    UserSubscription.drop_collection()
    o1 = Organization(name='o1').save()
    o2 = Organization(name='o2').save()
    u1 = User(name='Ross', orgs=[o1, o2]).save()
    f1 = Feed(name='MongoEngine').save()
    sub = UserSubscription(user=u1, feed=f1).save()
    user = User.objects.first()
    self.assertTrue(isinstance(user._data['orgs'][0], DBRef))
    self.assertTrue(isinstance(user.orgs[0], Organization))
    self.assertTrue(isinstance(user._data['orgs'][0], Organization))
    with query_counter() as q:
        self.assertEqual(q, 0)
        sub = UserSubscription.objects.first()
        self.assertEqual(q, 1)
        sub.name = 'Test    Sub'
        sub.save()
        self.assertEqual(q, 2)
    with query_counter() as q:
        self.assertEqual(q, 0)
        sub = UserSubscription.objects.first()
        self.assertEqual(q, 1)
        sub.user.name = 'Test'
        self.assertEqual(q, 2)
        sub.save(cascade=True)
        self.assertEqual(q, 3)
    with query_counter() as q:
        self.assertEqual(q, 0)
        sub = UserSubscription.objects.first()
        sub.name = 'Test    Sub    2'
        self.assertEqual(q, 1)
        sub.user.name = 'Test    2'
        self.assertEqual(q, 2)
        sub.save(cascade=True)
        self.assertEqual(q, 4)
    with query_counter() as q:
        self.assertEqual(q, 0)
        sub = UserSubscription(user=u1.pk, feed=f1.pk)
        self.assertEqual(q, 0)
        sub.save()
        self.assertEqual(q, 1)
    with query_counter() as q:
        self.assertEqual(q, 0)
        User(name='Bob', orgs=[o1.pk, o2.pk]).save()
        self.assertEqual(q, 1)
    with query_counter() as q:
        self.assertEqual(q, 0)
        user = User.objects.first()
        self.assertEqual(q, 1)
        feed = Feed.objects.first()
        self.assertEqual(q, 2)
        sub = UserSubscription(user=user, feed=feed)
        self.assertEqual(q, 2)
        sub.save()
        self.assertEqual(q, 3)
