def delete_stale_entries(model, pks_to_keep):
    """
    Deletes all model instances with primary keys (pks) not specified in pks_to_keep
    Returns the number of items deleted
    Note: Errors or race conditions may occur if table modifications occur during execution
    """
    stale = 0
    if model.objects.all().count() != len(pks_to_keep):
        for item in model.objects.all():
            if item.pk not in pks_to_keep:
                item.delete()
                stale += 1
    return stale
