Django

Code

Changeset 7871

Show
Ignore:
Timestamp:
07/08/08 16:53:38 (2 months ago)
Author:
gwilson
Message:

Fixed a couple typos as well as several minor style issues.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/db/models/base.py

    r7859 r7871  
    44import os 
    55from itertools import izip 
     6try: 
     7    set 
     8except NameError: 
     9    from sets import Set as set     # Python 2.3 fallback. 
    610 
    711import django.db.models.manipulators    # Imported to register signal handler. 
     
    2428from django.conf import settings 
    2529 
    26 try: 
    27     set 
    28 except NameError: 
    29     from sets import Set as set     # Python 2.3 fallback 
    3030 
    3131class ModelBase(type): 
    32     "Metaclass for all models" 
     32    """ 
     33    Metaclass for all models. 
     34    """ 
    3335    def __new__(cls, name, bases, attrs): 
    3436        super_new = super(ModelBase, cls).__new__ 
     
    145147 
    146148    def _prepare(cls): 
    147         # Creates some methods once self._meta has been populated. 
     149        """ 
     150        Creates some methods once self._meta has been populated. 
     151        """ 
    148152        opts = cls._meta 
    149153        opts._prepare(cls) 
     
    163167 
    164168        dispatcher.send(signal=signals.class_prepared, sender=cls) 
     169 
    165170 
    166171class Model(object): 
     
    268273    def save(self): 
    269274        """ 
    270         Save the current instance. Override this in a subclass if you want to 
     275        Saves the current instance. Override this in a subclass if you want to 
    271276        control the saving process. 
    272277        """ 
     
    294299        # If we are in a raw save, save the object exactly as presented. 
    295300        # That means that we don't try to be smart about saving attributes 
    296         # that might have come from the parent class - we just save the  
     301        # that might have come from the parent class - we just save the 
    297302        # attributes we have been given to the class we have been given. 
    298303        if not raw: 
     
    302307 
    303308        non_pks = [f for f in meta.local_fields if not f.primary_key] 
    304              
     309 
    305310        # First, try an UPDATE. If that doesn't update anything, do an INSERT. 
    306311        pk_val = self._get_pk_val(meta) 
     
    372377    def _collect_sub_objects(self, seen_objs, parent=None, nullable=False): 
    373378        """ 
    374         Recursively populates seen_objs with all objects related to this object. 
     379        Recursively populates seen_objs with all objects related to this 
     380        object. 
     381 
    375382        When done, seen_objs.items() will be in the format: 
    376383            [(model_class, {pk_val: obj, pk_val: obj, ...}), 
    377              (model_class, {pk_val: obj, pk_val: obj, ...}),...] 
     384             (model_class, {pk_val: obj, pk_val: obj, ...}), ...] 
    378385        """ 
    379386        pk_val = self._get_pk_val() 
     
    412419        assert self._get_pk_val() is not None, "%s object can't be deleted because its %s attribute is set to None." % (self._meta.object_name, self._meta.pk.attname) 
    413420 
    414         # Find all the objects than need to be deleted 
     421        # Find all the objects than need to be deleted. 
    415422        seen_objs = CollectedObjects() 
    416423        self._collect_sub_objects(seen_objs) 
    417424 
    418         # Actually delete the objects 
     425        # Actually delete the objects. 
    419426        delete_objects(seen_objs) 
    420427 
     
    455462 
    456463    def _get_FIELD_filename(self, field): 
    457         if getattr(self, field.attname): # value is not blank 
     464        if getattr(self, field.attname): # Value is not blank. 
    458465            return os.path.normpath(os.path.join(settings.MEDIA_ROOT, getattr(self, field.attname))) 
    459466        return '' 
    460467 
    461468    def _get_FIELD_url(self, field): 
    462         if getattr(self, field.attname): # value is not blank 
     469        if getattr(self, field.attname): # Value is not blank. 
    463470            import urlparse 
    464471            return urlparse.urljoin(settings.MEDIA_URL, getattr(self, field.attname)).replace('\\', '/') 
     
    475482            pass 
    476483 
    477         # 
    478484        # Check for old-style usage (files-as-dictionaries). Warn here first 
    479485        # since there are multiple locations where we need to support both new 
    480486        # and old usage. 
    481         # 
    482487        if isinstance(raw_field, dict): 
    483488            import warnings 
    484489            warnings.warn( 
    485490                message = "Representing uploaded files as dictionaries is"\ 
    486                           " deprected. Use django.core.files.SimpleUploadedFile"\ 
     491                          " deprecated. Use django.core.files.SimpleUploadedFile"\ 
    487492                          " instead.", 
    488493                category = DeprecationWarning, 
     
    509514        filename = field.get_filename(filename) 
    510515 
    511         # 
    512         # If the filename already exists, keep adding an underscore to the name of 
    513         # the file until the filename doesn't exist. 
    514         # 
     516        # If the filename already exists, keep adding an underscore to the name 
     517        # of the file until the filename doesn't exist. 
    515518        while os.path.exists(os.path.join(settings.MEDIA_ROOT, filename)): 
    516519            try: 
    517520                dot_index = filename.rindex('.') 
    518             except ValueError: # filename has no dot 
     521            except ValueError: # filename has no dot. 
    519522                filename += '_' 
    520523            else: 
    521524                filename = filename[:dot_index] + '_' + filename[dot_index:] 
    522         # 
    523         # Save the file name on the object and write the file to disk 
    524         # 
    525  
     525 
     526        # Save the file name on the object and write the file to disk. 
    526527        setattr(self, field.attname, filename) 
    527  
    528528        full_filename = self._get_FIELD_filename(field) 
    529  
    530529        if hasattr(raw_field, 'temporary_file_path'): 
    531530            # This file has a file path that we can move. 
    532531            raw_field.close() 
    533532            file_move_safe(raw_field.temporary_file_path(), full_filename) 
    534  
    535533        else: 
    536534            # This is a normal uploadedfile that we can stream. 
     
    543541 
    544542        # Save the width and/or height, if applicable. 
    545         if isinstance(field, ImageField) and (field.width_field or field.height_field): 
     543        if isinstance(field, ImageField) and \ 
     544                (field.width_field or field.height_field): 
    546545            from django.utils.images import get_image_dimensions 
    547546            width, height = get_image_dimensions(full_filename) 
     
    551550                setattr(self, field.height_field, height) 
    552551 
    553         # Save the object because it has changed unless save is False 
     552        # Save the object because it has changed, unless save is False. 
    554553        if save: 
    555554            self.save() 
     
    570569            setattr(self, cachename, get_image_dimensions(filename)) 
    571570        return getattr(self, cachename) 
     571 
    572572 
    573573############################################ 
     
    586586    transaction.commit_unless_managed() 
    587587 
     588 
    588589def method_get_order(ordered_obj, self): 
    589590    rel_val = getattr(self, ordered_obj._meta.order_with_respect_to.rel.field_name) 
     
    593594            ordered_obj.objects.filter(**{order_name: rel_val}).values(pk_name)] 
    594595 
     596 
    595597############################################## 
    596598# HELPER FUNCTIONS (CURRIED MODEL FUNCTIONS) # 
     
    599601def get_absolute_url(opts, func, self, *args, **kwargs): 
    600602    return settings.ABSOLUTE_URL_OVERRIDES.get('%s.%s' % (opts.app_label, opts.module_name), func)(self, *args, **kwargs) 
     603 
    601604 
    602605######## 
     
    611614    def subclass_exception(name, parent, unused): 
    612615        return types.ClassType(name, (parent,), {}) 
    613  
    614616else: 
    615617    def subclass_exception(name, parent, module): 
    616618        return type(name, (parent,), {'__module__': module}) 
    617  
  • django/trunk/django/db/models/query.py

    r7782 r7871  
    1414ITER_CHUNK_SIZE = CHUNK_SIZE 
    1515 
    16 # Pull into this namespace for backwards compatibility 
     16# Pull into this namespace for backwards compatibility. 
    1717EmptyResultSet = sql.EmptyResultSet 
    1818 
     
    2020    pass 
    2121 
     22 
    2223class CollectedObjects(object): 
    2324    """ 
    24     A container that stores keys and lists of values along with 
    25     remembering the parent objects for all the keys. 
    26  
    27     This is used for the database object deletion routines so that we 
    28     can calculate the 'leaf' objects which should be deleted first. 
     25    A container that stores keys and lists of values along with remembering the 
     26    parent objects for all the keys. 
     27 
     28    This is used for the database object deletion routines so that we can 
     29    calculate the 'leaf' objects which should be deleted first. 
    2930    """ 
    3031 
     
    3536    def add(self, model, pk, obj, parent_model, nullable=False): 
    3637        """ 
    37         Adds an item. 
    38         model is the class of the object being added, 
    39         pk is the primary key, obj is the object itself, 
    40         parent_model is the model of the parent object 
    41         that this object was reached through, nullable should 
    42         be True if this relation is nullable. 
    43  
    44         If the item already existed in the structure, 
    45         returns true, otherwise false. 
     38        Adds an item to the container. 
     39 
     40        Arguments: 
     41        * model - the class of the object being added. 
     42        * pk - the primary key. 
     43        * obj - the object itself. 
     44        * parent_model - the model of the parent object that this object was 
     45          reached through. 
     46        * nullable - should be True if this relation is nullable. 
     47 
     48        Returns True if the item already existed in the structure and 
     49        False otherwise. 
    4650        """ 
    4751        d = self.data.setdefault(model, SortedDict()) 
    4852        retval = pk in d 
    4953        d[pk] = obj 
    50         # Nullable relationships can be ignored -- they 
    51         # are nulled out before deleting, and therefore 
    52         # do not affect the order in which objects have 
    53         # to be deleted. 
     54        # Nullable relationships can be ignored -- they are nulled out before 
     55        # deleting, and therefore do not affect the order in which objects 
     56        # have to be deleted. 
    5457        if parent_model is not None and not nullable: 
    5558            self.children.setdefault(parent_model, []).append(model) 
    56  
    5759        return retval 
    5860 
     
    7880    def ordered_keys(self): 
    7981        """ 
    80         Returns the models in the order that they should be 
    81         dealth with i.e. models with no dependencies first
     82        Returns the models in the order that they should be dealt with (i.e. 
     83        models with no dependencies first)
    8284        """ 
    8385        dealt_with = SortedDict() 
     
    9294                    found = True 
    9395            if not found: 
    94                 raise CyclicDependency("There is a cyclic dependency of items to be processed.") 
     96                raise CyclicDependency( 
     97                    "There is a cyclic dependency of items to be processed.") 
    9598 
    9699        return dealt_with.keys() 
     
    98101    def unordered_keys(self): 
    99102        """ 
    100         Fallback for the case where is a cyclic dependency but we 
    101         don't care. 
     103        Fallback for the case where is a cyclic dependency but we don't  care. 
    102104        """ 
    103105        return self.data.keys() 
    104106 
     107 
    105108class QuerySet(object): 
    106     "Represents a lazy database lookup for a set of objects" 
     109    """ 
     110    Represents a lazy database lookup for a set of objects. 
     111    """ 
    107112    def __init__(self, model=None, query=None): 
    108113        self.model = model 
     
    117122    def __getstate__(self): 
    118123        """ 
    119         Allows the Queryset to be pickled. 
     124        Allows the QuerySet to be pickled. 
    120125        """ 
    121126        # Force the cache to be fully populated. 
     
    132137        # Since __len__ is called quite frequently (for example, as part of 
    133138        # list(qs), we make some effort here to be as efficient as possible 
    134         # whilst not messing up any existing iterators against the queryset. 
     139        # whilst not messing up any existing iterators against the QuerySet. 
    135140        if self._result_cache is None: 
    136141            if self._iter: 
     
    174179 
    175180    def __getitem__(self, k): 
    176         "Retrieve an item or slice from the set of results." 
     181        """ 
     182        Retrieves an item or slice from the set of results. 
     183        """ 
    177184        if not isinstance(k, (slice, int, long)): 
    178185            raise TypeError 
     
    265272        integer. 
    266273 
    267         If the queryset is already cached (i.e. self._result_cache is set) this 
     274        If the QuerySet is already cached (i.e. self._result_cache is set) this 
    268275        simply returns the length of the cached results set to avoid multiple 
    269276        SELECT COUNT(*) calls. 
     
    291298    def create(self, **kwargs): 
    292299        """ 
    293         Create a new object with the given kwargs, saving it to the database 
     300        Creates a new object with the given kwargs, saving it to the database 
    294301        and returning the created object. 
    295302        """ 
     
    426433    def dates(self, field_name, kind, order='ASC'): 
    427434        """ 
    428         Returns a list of datetime objects representing all available dates 
    429         for the given field_name, scoped to 'kind'. 
     435        Returns a list of datetime objects representing all available dates for 
     436        the given field_name, scoped to 'kind'. 
    430437        """ 
    431438        assert kind in ("month", "year", "day"), \ 
     
    442449    def none(self): 
    443450        """ 
    444         Returns an empty queryset. 
     451        Returns an empty QuerySet. 
    445452        """ 
    446453        return self._clone(klass=EmptyQuerySet) 
     
    486493        """ 
    487494        Returns a new QuerySet instance with filter_obj added to the filters. 
     495 
    488496        filter_obj can be a Q object (or anything with an add_to_query() 
    489497        method) or a dictionary of keyword lookup arguments. 
     
    501509    def select_related(self, *fields, **kwargs): 
    502510        """ 
    503         Returns a new QuerySet instance that will select related objects. If 
    504         fields are specified, they must be ForeignKey fields and only those 
     511        Returns a new QuerySet instance that will select related objects. 
     512 
     513        If fields are specified, they must be ForeignKey fields and only those 
    505514        related objects are included in the selection. 
    506515        """ 
     
    522531    def dup_select_related(self, other): 
    523532        """ 
    524         Copies the related selection status from the queryset 'other' to the 
    525         current queryset. 
     533        Copies the related selection status from the QuerySet 'other' to the 
     534        current QuerySet. 
    526535        """ 
    527536        self.query.select_related = other.query.select_related 
    528537 
    529538    def order_by(self, *field_names): 
    530         """Returns a new QuerySet instance with the ordering changed.""" 
     539        """ 
     540        Returns a new QuerySet instance with the ordering changed. 
     541        """ 
    531542        assert self.query.can_filter(), \ 
    532543                "Cannot reorder a query once a slice has been taken." 
     
    545556 
    546557    def extra(self, select=None, where=None, params=None, tables=None, 
    547             order_by=None, select_params=None): 
    548         """ 
    549         Add extra SQL fragments to the query. 
     558              order_by=None, select_params=None): 
     559        """ 
     560        Adds extra SQL fragments to the query. 
    550561        """ 
    551562        assert self.query.can_filter(), \ 
     
    557568    def reverse(self): 
    558569        """ 
    559         Reverses the ordering of the queryset. 
     570        Reverses the ordering of the QuerySet. 
    560571        """ 
    561572        clone = self._clone() 
     
    590601    def _merge_sanity_check(self, other): 
    591602        """ 
    592         Checks that we are merging two comparable queryset classes. By default 
     603        Checks that we are merging two comparable QuerySet classes. By default 
    593604        this does nothing, but see the ValuesQuerySet for an example of where 
    594605        it's useful. 
    595606        """ 
    596607        pass 
     608 
    597609 
    598610class ValuesQuerySet(QuerySet): 
     
    618630        retrieving. 
    619631 
    620         Called by the _clone() method after initialising the rest of the 
     632        Called by the _clone() method after initializing the rest of the 
    621633        instance. 
    622634        """ 
     
    658670            raise TypeError("Merging '%s' classes must involve the same values in each case." 
    659671                    % self.__class__.__name__) 
     672 
    660673 
    661674class ValuesListQuerySet(ValuesQuerySet): 
     
    682695        return clone 
    683696 
     697 
    684698class DateQuerySet(QuerySet): 
    685699    def iterator(self): 
     
    690704        Sets up any special features of the query attribute. 
    691705 
    692         Called by the _clone() method after initialising the rest of the 
     706        Called by the _clone() method after initializing the rest of the 
    693707        instance. 
    694708        """ 
     
    707721        return c 
    708722 
     723 
    709724class EmptyQuerySet(QuerySet): 
    710725    def __init__(self, model=None, query=None): 
     
    733748        # (it raises StopIteration immediately). 
    734749        yield iter([]).next() 
     750 
    735751 
    736752# QOperator, QNot, QAnd and QOr are temporarily retained for backwards 
     
    744760QOr = QAnd = QOperator 
    745761 
     762 
    746763def QNot(q): 
    747764    warnings.warn('Use ~q instead of QNot(q)', DeprecationWarning, stacklevel=2) 
    748765    return ~q 
    749766 
     767 
    750768def get_cached_row(klass, row, index_start, max_depth=0, cur_depth=0, 
    751         requested=None): 
     769                   requested=None): 
    752770    """ 
    753771    Helper function that recursively returns an object with the specified 
     
    775793    return obj, index_end 
    776794 
     795 
    777796def delete_objects(seen_objs): 
    778797    """ 
     
    783802        ordered_classes = seen_objs.keys() 
    784803    except CyclicDependency: 
    785         # if there is a cyclic dependency, we cannot in general delet
    786         # the objects.  However, if an appropriate transaction is set 
    787         # up, or if the database is lax enough, it will succeed. 
    788         # So for now, we go ahead and try anway. 
     804        # If there is a cyclic dependency, we cannot in general delete th
     805        # objects.  However, if an appropriate transaction is set up, or if the 
     806        # database is lax enough, it will succeed. So for now, we go ahead and 
     807        # try anyway. 
    789808        ordered_classes = seen_objs.unordered_keys() 
    790809 
     
    795814        obj_pairs[cls] = items 
    796815 
    797         # Pre notify all instances to be deleted 
     816        # Pre-notify all instances to be deleted. 
    798817        for pk_val, instance in items: 
    799818            dispatcher.send(signal=signals.pre_delete, sender=cls, 
     
    809828                update_query.clear_related(field, pk_list) 
    810829 
    811     # Now delete the actual data 
     830    # Now delete the actual data. 
    812831    for cls in ordered_classes: 
    813832        items = obj_pairs[cls] 
     
    832851    transaction.commit_unless_managed() 
    833852 
     853 
    834854def insert_query(model, values, return_id=False, raw_values=False): 
    835855    """ 
     
    841861    query.insert_values(values, raw_values) 
    842862    return query.execute_sql(return_id) 
    843