class Post(Dateframeable, Timestampable, Permalinkable, PopoloModel): """ A position that exists independent of the person holding it """ label = models.CharField(_("label"), max_length=128, help_text=_("A label describing the post")) role = models.CharField( _("role"), max_length=128, null=True, blank=True, help_text=_("The function that the holder of the post fulfills")) # reference to "http://popoloproject.com/schemas/organization.json#" organization = models.ForeignKey( model_path('Organization'), related_name='posts', help_text=_("The organization in which the post is held")) @property def slug_source(self): return self.label objects = PassThroughManager.for_queryset_class(PostQuerySet)() class Meta: abstract = True
class ContactDetail(Timestampable, Dateframeable, GenericRelatable, models.Model): """ A means of contacting an entity see schema at http://popoloproject.com/schemas/contact-detail.json# """ CONTACT_TYPES = Choices( ('ADDRESS', 'address', _('Address')), ('EMAIL', 'email', _('Email')), ('URL', 'url', _('Url')), ('MAIL', 'mail', _('Snail mail')), ('TWITTER', 'twitter', _('Twitter')), ('FACEBOOK', 'facebook', _('Facebook')), ('PHONE', 'phone', _('Telephone')), ('MOBILE', 'mobile', _('Mobile')), ('TEXT', 'text', _('Text')), ('VOICE', 'voice', _('Voice')), ('FAX', 'fax', _('Fax')), ('CELL', 'cell', _('Cell')), ('VIDEO', 'video', _('Video')), ('PAGER', 'pager', _('Pager')), ('TEXTPHONE', 'textphone', _('Textphone')), ) label = models.CharField( _("label"), max_length=512, blank=True, help_text=_("A human-readable label for the contact detail")) contact_type = models.CharField( _("type"), max_length=12, choices=CONTACT_TYPES, help_text=_("A type of medium, e.g. 'fax' or 'email'")) value = models.CharField( _("value"), max_length=512, help_text=_("A value, e.g. a phone number or email address")) note = models.CharField( _("note"), max_length=512, blank=True, help_text=_( "A note, e.g. for grouping contact details by physical location")) # array of items referencing "http://popoloproject.com/schemas/link.json#" sources = GenericRelation( 'Source', help_text="URLs to source documents about the contact detail") try: # PassTrhroughManager was removed in django-model-utils 2.4, see issue #22 objects = PassThroughManager.for_queryset_class( ContactDetailQuerySet)() except: objects = ContactDetailQuerySet.as_manager() def __str__(self): return u"{0} - {1}".format(self.value, self.contact_type)
class Genre(models.Model): """A user generated genre for an artist that is part of an artist review. Attributes: created: When the model object was created. genre: The user choice of genre, chosen from GENRE_CHOICES review: The review the genre choice is associated with objects: A custom Query manager. See managers.py for more detail. """ GENRE_CHOICES = [ ('avant garde', 'Avant Garde'), ('blues', 'Blues'), ('country', 'Country'), ('electronic', 'Electronic'), ('folk', 'Folk'), ('hip hop', 'Hip Hop'), ('jazz', 'Jazz'), ('pop', 'Pop'), ('r&b', 'R&B'), ('rock', 'Rock'), ] created = models.DateTimeField(auto_now_add=True) genre = models.CharField(max_length=20, choices=GENRE_CHOICES) review = models.ForeignKey(Review, related_name='genres') objects = PassThroughManager.for_queryset_class(GenreQuerySet)() def __unicode__(self): return self.genre
class Authorable(models.Model): class Meta: abstract = True objects = PassThroughManager.for_queryset_class(AuthorableQuerySet)() author = models.ForeignKey(settings.AUTH_USER_MODEL)
def MultiPassThroughManager(*classes): name = "".join([cls.__name__ for cls in classes]) if django.VERSION < (1, 7, 0): from model_utils.managers import PassThroughManager return PassThroughManager.for_queryset_class(type(name, classes, {}))() else: return type(name, classes, {}).as_manager()
class OtherName(models.Model): """An alternate or former name.""" name = models.CharField(_('name'), max_length=128, help_text=_('An alternate or former name')) note = models.CharField(_('note'), max_length=256, blank=True, null=True, help_text=_('A note, e.g. \'Birth name\'')) objects = PassThroughManager.for_queryset_class(OtherNameQuerySet)() person = models.ForeignKey('Person', blank=True, null=True, help_text='The person this name belongs to') organization = models.ForeignKey( 'Organization', blank=True, null=True, help_text='The organization this name belongs to') def __str__(self): return self.name
class Authorable(models.Model): author = models.ForeignKey(User, null=True) class Meta: abstract = True objects = PassThroughManager.for_queryset_class(AuthorableQuerySet)()
class Page(MPTTModel, Displayable, MetaInfo): template_override = models.CharField(max_length=255, null=True, blank=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children') url = models.CharField(max_length=255, null=True, blank=True) # Because we're not directly inheriting from Displayable, we need to make # sure the default manager is set. objects = PassThroughManager.for_queryset_class(SiteEntityQuerySet)() def update_url(self, save=True): self.url = self._url @property def _url(self): if self.is_root_node(): return reverse('suave:page') url = '{0}{1}/'.format( self.parent.url, self.slug ) return url def get_absolute_url(self): return self.url
class DemandProposition(models.Model): """ Representation of a demand Proposition""" user = models.ForeignKey(User, related_name='uservol') demand = models.ForeignKey(Demand, related_name='propositions') comment = models.TextField(verbose_name=_("Commentaire (facultatif)"), blank=True, null=True) created = models.DateTimeField(verbose_name=_("Date de création"), auto_now=True) accepted = models.BooleanField(verbose_name=_("Proposition acceptée"), default=False) km = models.IntegerField(verbose_name=_("Distance depuis domicile"), blank=True, null=True) time = MultiSelectField( choices=TIME_CHOICES, verbose_name=_("Heure(s) choisie(s)"), blank=False, help_text=_('Selectionnez les heures qui vous conviennent')) objects = PassThroughManager.for_queryset_class(DemandPropositionManager)() def get_verbose_time(self): if not self.time: return '' return ', '.join( [str(l[1]) for l in TIME_CHOICES if (str(l[0]) in self.time)]) class Meta: ordering = ['-created']
class Charge(NewsTargetMixin, models.Model): """ This is the base class for the different macro-types of charges (institution, organization, administration). The ``related_news`` attribute can be used to fetch news items related to a given charge. """ person = models.ForeignKey('Person', verbose_name=_('person')) start_date = models.DateField(_('start date')) end_date = models.DateField(_('end date'), blank=True, null=True) end_reason = models.CharField(_('end reason'), blank=True, max_length=255) description = models.CharField( _('description'), blank=True, max_length=255, help_text= _('Insert the complete description of the charge, if it gives more information than the charge type' )) objects = PassThroughManager.for_queryset_class(TimeFramedQuerySet)() class Meta: abstract = True def get_absolute_url(self): return self.person.get_absolute_url()
class report(models.Model): sol=models.IntegerField(primary_key=True) terrestrial_date=models.DateTimeField(null=True) objects=PassThroughManager.for_queryset_class(report_QuerySet)() def __unicode__(self): return str(self.sol)
class Spot(models.Model): name = models.CharField(max_length=20) secure = models.BooleanField(default=True) closed = models.BooleanField(default=False) owner = models.ForeignKey(Dude, related_name='spots_owned') objects = PassThroughManager.for_queryset_class(SpotQuerySet)()
class Job(models.Model): """ Representation of a job (demand or offer) """ branch = models.ForeignKey(Branch, verbose_name=_("Branche"), related_name="%(class)s_branch") donor = models.ForeignKey(User, verbose_name=_("Donneur"), related_name="%(class)s_donor", null=True, blank=True) receiver = models.ForeignKey(User, verbose_name=_("Receveur"), related_name="%(class)s_receiver", null=True, blank=True) description = models.TextField(verbose_name=_("Description"), blank=True, null=True) category = MultiSelectField(choices=JobCategory.JOB_CATEGORIES, verbose_name=_("Type d'aide")) receive_help_from_who = models.IntegerField(choices=MemberType.MEMBER_TYPES_GROUP, default=MemberType.ALL, verbose_name=_("Qui peut voir et répondre à la demande/offre ?")) date = models.DateTimeField(verbose_name=_("Date")) time = MultiSelectField(choices=TIME_CHOICES, verbose_name=_("Heures de disponibilité"), blank=False, help_text=_('Selectionnez les heures qui vous conviennent')) def get_verbose_category(self): if not self.category: return '' return ', '.join([str(l[1]) for l in JobCategory.JOB_CATEGORIES if (str(l[0]) in self.category)]) def get_verbose_time(self): if not self.time: return '' return ', '.join([str(l[1]) for l in TIME_CHOICES if (str(l[0]) in self.time)]) def get_short_time(self): if not self.time: return '' return ', '.join([str(SHORT_TIME[l[0]-1]) for l in TIME_CHOICES if (str(l[0]) in self.time)]) objects = PassThroughManager.for_queryset_class(JobManager)() class Meta: abstract = True
class Dude(models.Model): abides = models.BooleanField(default=True) name = models.CharField(max_length=20) has_rug = models.BooleanField(default=False) objects = PassThroughManager(DudeQuerySet) abiders = AbidingManager()
class WelcomeEmail(generics.EmailSendable, GrapevineModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="welcome_emails") try: # In Django 1.7, this is finally addressed! objects = WelcomeEmailQuerySet.as_manager() except AttributeError: # This handles Django <= 1.6 objects = PassThroughManager.for_queryset_class(WelcomeEmailQuerySet)() class Meta: verbose_name = "Welcome Email" verbose_name_plural = "Welcome Emails" def as_str(self): return "Welcome Email to {0}".format(self.user) def get_template_name(self): return "emails/welcome.html" def get_raw_subject(self): return "Welcome to Acme Inc, {{ sendable.user }}!" def get_recipients(self): return {"to": [self.user.email], "bcc": ["*****@*****.**"]} def confirm_individual_sendability(self): """Only send Welcome Emails to users with email addresses""" if not self.user.email: self.cancelled_at_send_time = True self.save() return bool(self.user.email)
class Organization(Timestampable, Taggable, models.Model): """A group with a common purpose or reason for existence that goes beyond the set of people belonging to it. """ name = models.TextField( _('name'), help_text=_('A primary name, e.g. a legally recognized name')) # array of items referencing "http://popoloproject.com/schemas/other_name.json#" acronym = models.CharField(_('acronym'), blank=True, null=True, max_length=128, help_text=_('Organization acronym')) gov_id = models.TextField(_('Gov website ID'), blank=True, null=True, help_text=_('Gov website ID')) classification = models.CharField( _('classification'), max_length=128, blank=True, null=True, help_text=('An organization category, e.g. committee')) # reference to "http://popoloproject.com/schemas/organization.json#" parent = models.ForeignKey( 'Organization', blank=True, null=True, related_name='children', help_text=_('The organization that contains this organization')) dissolution_date = PopoloDateTimeField( blank=True, null=True, help_text=_('A date of dissolution')) founding_date = PopoloDateTimeField(blank=True, null=True, help_text=_('A date of founding')) # array of items referencing "http://popoloproject.com/schemas/contact_detail.json#" description = models.TextField(blank=True, null=True, help_text='Organization description') is_coalition = models.IntegerField( blank=True, null=True, help_text='1 if coalition, -1 if not, 0 if it does not apply') url_name = 'organization-detail' objects = PassThroughManager.for_queryset_class(OrganizationQuerySet)() def __str__(self): return self.name + " " + unicode(self.id)
class Membership(Timestampable, models.Model): """A relationship between a person and an organization.""" label = models.CharField(_('label'), max_length=128, blank=True, null=True, help_text=_('A label describing the membership')) role = models.CharField( _('role'), max_length=128, blank=True, null=True, help_text=_('The role that the person fulfills in the organization')) # reference to "http://popoloproject.com/schemas/person.json#" person = models.ForeignKey( 'Person', blank=True, null=True, related_name='memberships', help_text=_('The person who is a party to the relationship')) # reference to "http://popoloproject.com/schemas/organization.json#" organization = models.ForeignKey( 'Organization', blank=True, null=True, related_name='memberships', help_text=_('The organization that is a party to the relationship')) on_behalf_of = models.ForeignKey( 'Organization', blank=True, null=True, related_name='memberships_on_behalf_of', help_text= _('The organization on whose behalf the person is a party to the relationship' )) # start and end time of memberships start_time = PopoloDateTimeField(blank=True, null=True, help_text='Start time') end_time = PopoloDateTimeField(blank=True, null=True, help_text='End time') # array of items referencing "http://popoloproject.com/schemas/contact_detail.json#" @property def slug_source(self): return self.label objects = PassThroughManager.for_queryset_class(MembershipQuerySet)() def __str__(self): return u'Person: {0}, Org: {1}, StartTime: {2}'.format( self.person, self.organization, self.start_time.date() if self.start_time else "")
class BlogPost(Authorable, Permalinkable, Timestampable, Publishable, models.Model): title = models.CharField(max_length=255) body = models.TextField() url_name = "blog-post" @property def slug_source(self): return self.title objects = PassThroughManager.for_queryset_class(BlogPostQuerySet)()
class MininewsModel(StatusModel, TimeStampedModel): STATUS = Choices('draft', 'published') start = models.DateField('start date', null=True, blank=True) end = models.DateField('end date', null=True, blank=True) objects = PassThroughManager.for_queryset_class(MininewsQuerySet)() class Meta: abstract = True def save(self, *args, **kwargs): """Set the start date for non-draft items if it hasn't been set already.""" if self.status != self.STATUS.draft and self.start is None: self.start = datetime.date.today() super(MininewsModel, self).save(*args, **kwargs) def clean(self): super(MininewsModel, self).clean() if self.start and self.end and self.start > self.end: raise ValidationError( 'The end date cannot be before the start date.') def live(self, statuses=['published']): if self.status not in statuses: return False if self.start and self.start > datetime.date.today(): return False if self.end and self.end < datetime.date.today(): return False return True live.boolean = True @property def staff_preview(self): """Helper property - says if this object is being previewed by a member of staff. Can be used when displaying objects in the website - members of staff will see all objects, using this property in the template can help for attaching a message/custom CSS saying that this object is being previewed. For example, in the example_project we have this snippet: .. code-block:: django {% if article.staff_preview %} <div class="label label-warning">This is a preview</div> {% endif %} """ return self.status == self.STATUS.draft
class GroupCharge(models.Model): """ This model records the historical composition of council groups. This only makes sense for ``InstitutionCharges``. """ group = models.ForeignKey('Group') charge = models.ForeignKey('InstitutionCharge') charge_description = models.CharField(blank=True, max_length=255) start_date = models.DateField() end_date = models.DateField(blank=True, null=True) end_reason = models.CharField(blank=True, max_length=255) objects = PassThroughManager.for_queryset_class(TimeFramedQuerySet)() @property def responsabilities(self): return self.groupresponsability_set.all() def get_current_responsability(self, moment=None): """ Returns the current group responsability, if any """ if self.responsabilities.current(moment=moment).count() == 0: return None if self.responsabilities.current(moment=moment).count() == 1: return self.responsabilities.current(moment=moment)[0] raise MultipleObjectsReturned current_responsability = property(get_current_responsability) @property def responsability(self): if self.responsabilities.count() == 1: r = self.responsabilities[0] s = "%s: %s - %s" % (r.get_charge_type_display(), r.start_date, r.end_date) return s else: return "" class Meta: db_table = u'people_group_charge' verbose_name = _('group charge') verbose_name_plural = _('group charges') def __unicode__(self): if self.responsability: return "%s - %s - %s" % (self.group.acronym, self.charge.person.last_name, self.responsability) else: return "%s - %s" % (self.group.acronym, self.charge.person.last_name)
class Post(Timestampable, Taggable, models.Model): """A position that exists independent of the person holding it.""" label = models.CharField(_('label'), max_length=128, blank=True, null=True, help_text=_('A label describing the post')) role = models.CharField( _('role'), max_length=128, blank=True, null=True, help_text=_('The function that the holder of the post fulfills')) # reference to "http://popoloproject.com/schemas/organization.json#" organization = models.ForeignKey( 'Organization', blank=True, null=True, related_name='posts', help_text=_('The organization in which the post is held')) # reference to "http://popoloproject.com/schemas/post.json#" membership = models.ForeignKey( 'Membership', blank=True, null=True, related_name='memberships', help_text= _('The post held by the person in the organization through this membership' )) # start and end time of memberships start_time = PopoloDateTimeField(blank=True, null=True, help_text='Start time') end_time = PopoloDateTimeField(blank=True, null=True, help_text='End time') objects = PassThroughManager.for_queryset_class(PostQuerySet)() def add_person(self, person): m = Membership(post=self, person=person, organization=self.organization) m.save() def __str__(self): return u'Org: {0}, Role: {1}, Person: {2}'.format( self.membership.organization if self.membership else self.organization, self.role, self.membership.person.name if self.membership else "None")
class OtherName(Dateframeable, GenericRelatable, models.Model): """ An alternate or former name see schema at http://popoloproject.com/schemas/name-component.json# """ name = models.CharField(_("name"), max_length=512, help_text=_("An alternate or former name")) note = models.CharField(_("note"), max_length=1024, blank=True, help_text=_("A note, e.g. 'Birth name'")) objects = PassThroughManager.for_queryset_class(OtherNameQuerySet)() def __str__(self): return self.name
class Membership(Dateframeable, Timestampable, PopoloModel): """ A relationship between a person and an organization """ label = models.CharField(_("label"), max_length=128, null=True, blank=True, help_text=_("A label describing the membership")) role = models.CharField( _("role"), max_length=128, null=True, blank=True, help_text=_("The role that the person fulfills in the organization")) # reference to "http://popoloproject.com/schemas/person.json#" person = models.ForeignKey( model_path('Person'), related_name='memberships', help_text=_("The person who is a party to the relationship")) # reference to "http://popoloproject.com/schemas/organization.json#" organization = models.ForeignKey( model_path('Organization'), related_name='memberships', help_text=_("The organization that is a party to the relationship")) on_behalf_of = models.ForeignKey( model_path('Organization'), related_name='memberships_on_behalf_of', help_text= _("The organization on whose behalf the person is a party to the relationship" )) # reference to "http://popoloproject.com/schemas/post.json#" post = models.ForeignKey( model_path('Post'), null=True, related_name='memberships', help_text= _("The post held by the person in the organization through this membership" )) @property def slug_source(self): return self.label objects = PassThroughManager.for_queryset_class(MembershipQuerySet)() class Meta: abstract = True
class EffectiveRangeMixin(models.Model, DateRangeMixin): """ Mixin adding an 'effective from' and 'effective to' pair of fields that implement DateRangeMixin. """ effective_from = models.DateTimeField( db_column='effective_from', null=True, blank=True, default=timezone.now(), help_text="""The date from which this item applies. If this is not given, then the item is inert, which is usually the case when it has not been approved. """) effective_to = models.DateTimeField( db_column='effective_to', null=True, blank=True, help_text="""The date on which this credit ceases to apply, if any. """) def range_start(self): return self.effective_from def range_end(self): return self.effective_to @classmethod def in_range(cls, from_date, to_date, queryset=None): """Compatibility wrapper for QuerySet.in_range.""" if queryset is None: queryset = cls.objects return queryset.in_range(from_date, to_date) @classmethod def at(cls, date, queryset=None): """Compatibility wrapper for QuerySet.at.""" if queryset is None: queryset = cls.objects return queryset.at(date) objects = PassThroughManager.for_queryset_class(ERQuerySet)() class Meta(object): get_latest_by = 'effective_from' abstract = True
class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) birthday = models.DateField() objects = PassThroughManager(PersonQuerySet) def __str__(self): return '%s %s, Birthday: %s' % (self.first_name, self.last_name, self.birthday) class Meta: ordering = ('last_name', )
def MultiPassThroughManager(*classes): name = "".join([cls.__name__ for cls in classes]) if django.VERSION < (1, 7, 0): from model_utils.managers import PassThroughManager result_class = PassThroughManager.for_queryset_class(type(name, classes, {})) result = result_class() else: result_class = type(name, classes, {}) result = result_class.as_manager() globals()[name] = result_class return result
def MultiPassThroughManager(*classes): name = "".join([cls.__name__ for cls in classes]) if django.VERSION < (1, 7, 0): from model_utils.managers import PassThroughManager result_class = PassThroughManager.for_queryset_class( type(name, classes, {})) result = result_class() else: result_class = type(name, classes, {}) result = result_class.as_manager() globals()[name] = result_class return result
class Membership(Dateframeable, Timestampable, models.Model): """ A relationship between a person and an organization see schema at http://popoloproject.com/schemas/membership.json# """ label = models.CharField(_("label"), max_length=512, blank=True, help_text=_("A label describing the membership")) role = models.CharField(_("role"), max_length=512, blank=True, help_text=_("The role that the person fulfills in the organization")) # reference to "http://popoloproject.com/schemas/person.json#" person = models.ForeignKey('Person', to_field="id", related_name='memberships', help_text=_("The person who is a party to the relationship")) # reference to "http://popoloproject.com/schemas/organization.json#" organization = models.ForeignKey('Organization', blank=True, null=True, related_name='memberships', help_text=_("The organization that is a party to the relationship")) on_behalf_of = models.ForeignKey('Organization', blank=True, null=True, related_name='memberships_on_behalf_of', help_text=_("The organization on whose behalf the person is a party to the relationship")) # reference to "http://popoloproject.com/schemas/post.json#" post = models.ForeignKey('Post', blank=True, null=True, related_name='memberships', help_text=_("The post held by the person in the organization through this membership")) # reference to "http://popoloproject.com/schemas/area.json#" area = models.ForeignKey('Area', blank=True, null=True, related_name='memberships', help_text=_("The geographic area to which the post is related")) # array of items referencing "http://popoloproject.com/schemas/contact_detail.json#" contact_details = generic.GenericRelation('ContactDetail', help_text="Means of contacting the member of the organization") # array of items referencing "http://popoloproject.com/schemas/link.json#" links = generic.GenericRelation('Link', help_text="URLs to documents about the membership") # array of items referencing "http://popoloproject.com/schemas/link.json#" sources = generic.GenericRelation('Source', help_text="URLs to source documents about the membership") @property def slug_source(self): return self.label objects = PassThroughManager.for_queryset_class(MembershipQuerySet)() def __str__(self): return self.label
class Header(models.Model): """Header model ordinal preserves the order of headers as in the original message Object manager has a create() method that accepts name and data, it deals with duplicated header names/data behind the scenes """ name = models.ForeignKey(HeaderName, on_delete=models.PROTECT) data = models.ForeignKey(HeaderData, on_delete=models.PROTECT) part = models.ForeignKey(PartList) ordinal = models.IntegerField() objects = PassThroughManager.for_queryset_class(HeaderQuerySet)() def __unicode__(self): return u"{0}".format(self.name.name)
class O2OTag(models.Model): # The object that is tagging tagger_content_type = models.ForeignKey(ContentType, related_name="taggers") tagger_object_id = models.PositiveIntegerField() tagger_content_object = generic.GenericForeignKey("tagger_content_type", "tagger_object_id") # The object that is tagged tagged_content_type = models.ForeignKey(ContentType, related_name="taggeds") tagged_object_id = models.PositiveIntegerField() tagged_content_object = generic.GenericForeignKey("tagged_content_type", "tagged_object_id") # The object where the tagged objects is tagged tagged_in_content_type = models.ForeignKey(ContentType, related_name="tags") tagged_in_object_id = models.PositiveIntegerField() tagged_in_content_object = generic.GenericForeignKey( "tagged_in_content_type", "tagged_in_object_id") created_at = models.DateTimeField(auto_now_add=True) objects = PassThroughManager.for_queryset_class(O2OTagQuerySet)() class Meta: unique_together = ('tagger_content_type', 'tagger_object_id', 'tagged_content_type', 'tagged_object_id', 'tagged_in_content_type', 'tagged_in_object_id') def __unicode__(self): return u'%s -> %s | %s' % (self.tagger, self.tagged, self.tagged_in) # Convenient shortcuts @property def tagged(self): return self.tagged_content_object @property def tagger(self): return self.tagger_content_object @property def tagged_in(self): return self.tagged_in_content_object
class Post(Dateframeable, Timestampable, models.Model): """ A position that exists independent of the person holding it see schema at http://popoloproject.com/schemas/json# """ id = AutoSlugField( populate_from=lambda instance: instance.slug_source, primary_key=True, max_length=256, slugify=slugify ) @property def slug_source(self): return self.label label = models.CharField(_("label"), max_length=512, blank=True, help_text=_("A label describing the post")) other_label = models.CharField(_("other label"), max_length=512, blank=True, null=True, help_text=_("An alternate label, such as an abbreviation")) role = models.CharField(_("role"), max_length=512, blank=True, help_text=_("The function that the holder of the post fulfills")) # reference to "http://popoloproject.com/schemas/organization.json#" organization = models.ForeignKey('Organization', related_name='posts', help_text=_("The organization in which the post is held")) # reference to "http://popoloproject.com/schemas/area.json#" area = models.ForeignKey('Area', blank=True, null=True, related_name='posts', help_text=_("The geographic area to which the post is related")) # array of items referencing "http://popoloproject.com/schemas/contact_detail.json#" contact_details = generic.GenericRelation('ContactDetail', help_text="Means of contacting the holder of the post") # array of items referencing "http://popoloproject.com/schemas/link.json#" links = generic.GenericRelation('Link', help_text="URLs to documents about the post") # array of items referencing "http://popoloproject.com/schemas/link.json#" sources = generic.GenericRelation('Source', help_text="URLs to source documents about the post") objects = PassThroughManager.for_queryset_class(PostQuerySet)() def add_person(self, person): m = Membership(post=self, person=person, organization=self.organization) m.save() def __str__(self): return self.label
""" Group by incident date. Pass in a format to create larger groups (months, for example). """ if format: return groupby(self, lambda v: v.incident.datetime.strftime(format)) else: return groupby(self, lambda v: v.incident.datetime) def by_incident(self): """ Group by incident ID. """ return groupby(self, lambda v: v.incident_id) def public(self): return self.filter(public=True, incident__isnull=False) class IncidentQuerySet(GeoQuerySet): """ A queryset for incidents, which needs spatial stuff and publicness """ def public(self): return self.filter(public=True) PersonManager = PassThroughManager.for_queryset_class(PersonQuerySet) VictimManager = PassThroughManager.for_queryset_class(VictimQuerySet) IncidentManager = PassThroughManager.for_queryset_class(IncidentQuerySet)
return super().count() cursor = connections[self.db].cursor() sqlquery = ( "SELECT reltuples FROM pg_class ", "WHERE relname = '{}';".format(self.model._meta.db_table) ) cursor.execute(''.join(sqlquery)) count_estimate = int(cursor.fetchone()[0]) if int(count_estimate) < 50000: return super().count() else: return count_estimate MyCountManager = PassThroughManager.for_queryset_class(MyFuzzyCountManager) class Measurement(models.Model): """ A measurement on a meter port """ meter_port = models.ForeignKey( MeterPort, related_name="measurement", db_index=True, ) timestamp = models.DateTimeField(db_index=True) value = models.BigIntegerField() created = models.DateTimeField(auto_now_add=True, db_index=True) last_modified = models.DateTimeField(auto_now=True)
def MultiPassThroughManager(*classes): from model_utils.managers import PassThroughManager name = "".join([cls.__name__ for cls in classes]) return PassThroughManager.for_queryset_class(type(name, classes, {}))()
class CandidateQuerySet(models.query.QuerySet): def order_by_wins(self): return self.extra(select={ 'win_pct': 'wins / votes', }).order_by( '-win_pct') def for_category(self, category): return self.filter(category=category) def enabled(self): return self.filter(is_enabled=True) CandidateManager = PassThroughManager.for_queryset_class(CandidateQuerySet) class EnabledCandidateManager(CandidateManager): def get_queryset(self): return super(EnabledCandidateManager, self).get_queryset().enabled() class Candidate(models.Model): name = models.CharField(max_length=100) slug = AutoSlugField(populate_from='name', unique=True, blank=True) pic = ImageField(upload_to='candidates') is_enabled = models.BooleanField(default=True) category = models.ForeignKey(CandidateCategory, related_name='candidates')
from django.conf import settings from django.db import connections from django.db.models.query import QuerySet from model_utils.managers import PassThroughManager class FuzzyCountQuerySet(QuerySet): def count(self): is_postgresql = settings.DATABASES[self.db]["ENGINE"].endswith(("postgis", "postgresql")) is_filtered = self.query.where or self.query.having if not is_postgresql or is_filtered: return super(FuzzyCountQuerySet, self).count() cursor = connections[self.db].cursor() cursor.execute("SELECT reltuples FROM pg_class " "WHERE relname = '%s';" % self.model._meta.db_table) return int(cursor.fetchone()[0]) FuzzyCountManager = PassThroughManager.for_queryset_class(FuzzyCountQuerySet)