Пример #1
0
class Migration(migrations.Migration):

    dependencies = [
        ('fk', '0003_asrun'),
    ]

    operations = [
        migrations.AlterField(
            model_name='scheduleitem',
            name='duration',
            field=DurationField(),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='video',
            name='duration',
            field=DurationField(),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='weeklyslot',
            name='duration',
            field=DurationField(),
            preserve_default=True,
        ),
        migrations.RunPython(duration_millisecond_to_microsecond),
    ]
Пример #2
0
class Stat(Model):
    length = DurationField(default=0)
    spoken = DurationField(default=0)
    ad_count = IntegerField(default=0)
    song_cat3 = IntegerField(default=0)
    song_cat2 = IntegerField(default=0)
    song_cat3_canadian = IntegerField(default=0)
    song_cat2_canadian = IntegerField(default=0)
    song_local = IntegerField(default=0)

    def __str__(self):
        return "Stat:  (spoken: %s of %s), (local: %s of %s), (can2: %s of %s), (can3: %s of %s), (ads: %s)" % (
            str(self.spoken), str(self.length), self.song_local, self.song_cat3
            + self.song_cat2, self.song_cat2_canadian, self.song_cat2,
            self.song_cat3_canadian, self.song_cat3, self.ad_count)
Пример #3
0
class TicketProduct(Product):
    ticket = models.ForeignKey(TicketType)
    amount = models.PositiveIntegerField(
        help_text=_("Amount of tickets included in this product."))
    duration = DurationField(
        blank=True,
        null=True,
        help_text=
        _("Relative duration of the given product. For example 30 days, 90 days. If this is empty, you must insert expire date."
          ))
    expires = models.DateField(
        blank=True,
        null=True,
        help_text=
        _("Absolute expiration date for the given product. For example 2014-12-31. If this is empty, you must insert duration."
          ))

    class Meta:
        pass

    def clean(self):
        if not (self.duration or self.expires):
            raise ValidationError(
                _("Ticket duration or absolute expire date must be set"))

    def get_activator(self):
        return TicketProductActivator()
Пример #4
0
class Other(Model):
    spoken = BooleanField(
        choices=((True, 'S'), (False, 'M')),
        default=True,
    )

    description = CharField(max_length=120)
    length = DurationField()

    def cname(self):
        return self.__class__.__name__

    def __str__(self):
        return "%s [%s]" % (self.description, str(self.length)[:7])
class Ticket(models.Model):  #Model for Ticket Management System
    user_id = models.ForeignKey(User)
    topic_id = models.ForeignKey(Category)
    message = models.TextField()
    ticket_id = models.IntegerField()
    file_uploads = models.FileField(upload_to='tickets/file', blank=True)
    created_date_time = models.DateTimeField(auto_now_add=True)
    overdue_date_time = models.DateTimeField(auto_now_add=True)
    closed_date_time = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=20)  #open,closed,overdue
    reopened_date_time = models.DateTimeField(auto_now_add=True)
    topic_priority = models.CharField(max_length=20)  #low,high
    duration_for_reply = DurationField()

    def __unicode__(self):
        return self.user_id.username
Пример #6
0
class Ride(models.Model):
    user = models.ForeignKey('riders.Teammate', verbose_name = 'teammate')
    date = models.DateField('date', help_text = 'Date format: YYYY-MM-DD')
    # TODO what if we made this a list of foreign keys for other riders?
    buddies = models.CharField('ride buddies', max_length = 300)
    miles = models.DecimalField('miles ridden', max_digits = 5, decimal_places = 2)
    pace = models.DecimalField('average pace', max_digits = 3, decimal_places = 1)
    duration = DurationField('time to complete ride', help_text = 'HH:MM:SS format')
    comments = models.TextField('comments')
    time_logged = models.DateTimeField('date logged', auto_now_add = True, blank = True, null = True)

    # Method to create a new ride
    def log(cls, user, date, buddies, miles, pace, duration, comments):
        user_data = cls(user = user, date = date, buddies = buddies, miles = miles,
                   pace = pace, duration = duration, comments = comments)
        return user_data

    # Metadata for the visual names
    class Meta:
        verbose_name = 'ride'
        verbose_name_plural = 'rides'

    # Base method returns the teammate's name
    def __unicode__(self):
        # Returns the user foreign key, which calls __unicide__ in auth
        return '%s, %d miles' % (self.user, self.miles)

    # Methods to return model values
    def get_miles(self):
        # Returns the miles ridden
        return self.miles

    def get_date(self):
        # Returns the date the ride was on
        return self.date

    def get_pace(self):
        # Returns the pace for the ride
        return self.pace

    def get_duration(self):
        # Returns the time it took to ride
        return self.duration
        
    def get_time_logged(self):
        # Returns the time the ride was logged at
        return self.time_logged
Пример #7
0
class StationID(Model):
    spoken = BooleanField(
        choices=((True, 'S'), (False, 'M')),
        default=True,
    )

    description = CharField(max_length=120)
    length = DurationField()

    def cname(self):
        return self.__class__.__name__

    def __str__(self):
        if self.spoken:
            return "Spoken ID: %s %s" % (self.description, str(
                self.length)[2:7])
        else:
            return "Musical ID: %s %s" % (self.description, str(
                self.length)[2:7])
Пример #8
0
class Advertisement(Model):
    advertiser = CharField(max_length=40)
    length = DurationField()
    spoken = BooleanField(
        choices=((True, 'S'), (False, 'M')),
        default=True,
    )

    # required by section 8.1.c.v
    category = IntegerField(choices=((51, "Ad"), (52, "Sponsor ID"),
                                     (53, "Promo")),
                            default=52)

    def cname(self):
        return self.__class__.__name__

    def __str__(self):
        return "%s, %s [%s]" % (self.get_category_display(), self.advertiser,
                                str(self.length)[2:7])
Пример #9
0
class WeeklySlot(models.Model):
    DAY_OF_THE_WEEK = (
        (0, _(u'Monday')),
        (1, _(u'Tuesday')),
        (2, _(u'Wednesday')),
        (3, _(u'Thursday')),
        (4, _(u'Friday')),
        (5, _(u'Saturday')),
        (6, _(u'Sunday')),
    )

    purpose = models.ForeignKey(SchedulePurpose, null=True, blank=True)
    day = models.IntegerField(choices=DAY_OF_THE_WEEK, )
    start_time = models.TimeField()
    duration = DurationField()

    class Meta:
        ordering = ('day', 'start_time', 'pk')

    @property
    def end_time(self):
        if not self.duration:
            return self.start_time
        return self.start_time + self.duration

    def next_date(self, from_date=None):
        if not from_date:
            from_date = datetime.date.today()
        days_ahead = self.day - from_date.weekday()
        if days_ahead <= 0:
            # target date already happened this week
            days_ahead += 7
        return from_date + datetime.timedelta(days_ahead)

    def next_datetime(self, from_date=None):
        next_date = self.next_date(from_date)
        naive_dt = datetime.datetime.combine(next_date, self.start_time)
        tz = pytz.timezone(settings.TIME_ZONE)
        return tz.localize(naive_dt)

    def __unicode__(self):
        return (u"{day} {s.start_time} ({s.purpose})"
                u"".format(day=self.get_day_display(), s=self))
Пример #10
0
class Response(models.Model):
    """
    Response to a Survey. A Response is composed of multiple Answers
    to Questions.
    """
    objects = ResponseManager()

    slug = models.SlugField()
    created_at = models.DateTimeField(auto_now_add=True)
    survey = models.ForeignKey(SurveyModel, null=True)
    user = models.ForeignKey(AUTH_USER_MODEL, null=True)
    time_spent = DurationField(default=0,
        help_text="Total recorded time to complete the survey")
    is_frozen = models.BooleanField(default=False,
        help_text="When True, answers to that response cannot be updated.")

    def __unicode__(self):
        return self.slug

    def get_answers_by_rank(self):
        return self.answers.all().order_by('index') #pylint:disable=no-member
Пример #11
0
class Release(models.Model):
    name = models.CharField(max_length=255, blank=False)
    release_date = models.DateField(auto_now=False)
    creator = models.ForeignKey('ReleaseCreator',
                                on_delete=models.PROTECT,
                                blank=False)
    group_creator = models.ForeignKey('GroupCreator',
                                      on_delete=models.PROTECT,
                                      blank=False)
    length = DurationField(blank=True)
    cover_url = models.CharField(max_length=500, blank=True)
    review = models.ForeignKey('Review',
                               on_delete=models.PROTECT,
                               blank=True,
                               null=True)

    class Meta:
        abstract = True

    def __str__(self):
        return self.name
Пример #12
0
class Scheduleitem(models.Model):
    SCHEDULE_REASONS = (
        (1, 'Legacy'),
        (2, 'Administrative'),
        (3, 'User'),
        (4, 'Automatic'),
    )

    id = models.AutoField(primary_key=True)
    default_name = models.CharField(max_length=255, blank=True)
    video = models.ForeignKey(Video, null=True, blank=True)
    schedulereason = models.IntegerField(blank=True, choices=SCHEDULE_REASONS)
    starttime = models.DateTimeField()
    duration = DurationField()

    objects = ScheduleitemManager()
    """
    def save(self, *args, **kwargs):
        self.endtime = self.starttime + timeutils.duration
        super(Scheduleitem, self).save(*args, **kwargs)
    """
    class Meta:
        db_table = u'ScheduleItem'
        verbose_name = u'TX schedule entry'
        verbose_name_plural = u'TX schedule entries'

    def __unicode__(self):
        t = self.starttime
        s = t.strftime("%Y-%m-%d %H:%M:%S")
        # format microsecond to hundreths
        s += ".%02i" % (t.microsecond / 10000)
        if self.video:
            return str(s) + ": " + unicode(self.video)
        else:
            return str(s) + ": " + self.default_name

    def endtime(self):
        if not self.duration:
            return self.starttime
        return self.starttime + self.duration
Пример #13
0
class Song(Model):
    title = CharField(max_length=40)
    artist = CharField(max_length=40)
    composer = CharField(max_length=40)
    length = DurationField()

    category_3 = BooleanField(default=False,
                              choices=((True, '3'), (False, '2')))
    origin = CharField(max_length=3,
                       choices=(("Lcl", "Local"), ("Can", "Canadian"),
                                ("Int", "International")),
                       default="Int")
    hit = BooleanField(default=False)
    # instrumental pieces must be marked!  Do it here.
    language = CharField(max_length=20, default="english")

    def cname(self):
        return self.__class__.__name__

    def __str__(self):
        return "%s (%s) [%s]" % (self.title, self.artist, str(
            self.length)[2:7])
Пример #14
0
class TicketProductActivator(ProductActivator):
    start = models.PositiveIntegerField(null=True)
    end = models.PositiveIntegerField(null=True)
    rider = models.ForeignKey(RiderInfo, null=True, blank=True)
    duration = DurationField(blank=True, null=True)

    def activate(self):
        user = UserProfile.objects.find(
            _getUserName(self.order.shipping_address_text))
        if user:
            self.rider = user.rider
            for i in range(0, self.product.amount):
                exp = None
                if self.product.expires:
                    exp = self.product.expires
                t = Ticket.objects.create(type=self.product.ticket,
                                          owner=self.rider,
                                          expires=exp)
                if i == 0: self.start = t.id
                if i == self.product.amount - 1: self.end = t.id
            self.duration = self.product.duration
            self.status = self.ACTIVATED
            self.save()
Пример #15
0
class Lesson(CreatedMixin, Displayable):
    #TODO: this model should probably have a slug
    #title included thanks to displayable
    teacher = models.ForeignKey(User, related_name='teaching')
    image = models.FileField(upload_to=file_url("lessonimage"))
    flavor_text = models.TextField(default="")
    price = models.DecimalField(max_digits=20, decimal_places=2, null=True,
                                blank=True)
    users_who_rated = models.ManyToManyField(User, through='LessonRating',
                                             related_name='rated_lessons')

    followers = models.ManyToManyField(User, related_name='lessons',
                                       blank=True, null=True)
    serving_size = models.IntegerField()

   #tags = models.ChraField(max_length=128, default="")

    prep_time = DurationField()
    cooking_time = DurationField()

    primary_ingredients = models.ManyToManyField(Ingredient, related_name='primary_lessons', blank=True)
    course = models.ManyToManyField('Course', blank=True)
    cuisine = models.ManyToManyField('Cuisine', blank=True)
    restrictions = models.ManyToManyField("DietaryRestrictions", blank=True)

    kind = models.SmallIntegerField(choices=((0, "Recipe"),
                                             (1, "Technique")), default=0)

    ingredients = models.ManyToManyField(Ingredient, through="LessonIngredient", related_name="lessons")
    tools = models.ManyToManyField(Tool, through="LessonTool", related_name="lessons", blank=True)
    video = models.ForeignKey(Video, related_name="lessons", null=True, blank=True)


    class Meta():
        unique_together = ('teacher', 'title')

    @cached_property
    def tags(self):
        """Grabs a list of the lessons dietary restrictions, cuisines, courses,
        and primary ingredients from the database"""
        primary_ingredients = self.primary_ingredients.all()
        course = self.course.all()
        cuisine = self.cuisine.all()
        restrictions = self.restrictions.all()
        #list it to prevent caching the generator
        return list(chain(primary_ingredients, course, cuisine, restrictions))

    @property
    def rating(self):
        #TODO: user proper rating algo. http://www.evanmiller.org/how-not-to-sort-by-average-rating.html
        result = self.ratings.aggregate(avg=Avg('rating'))['avg']
        if not result:
            return 0
        return int(result)

    @property
    def prep_in_min(self):
        return int(max(self.prep_time.total_seconds() / 60, 1))

    @property
    def cook_in_min(self):
        return int(max(self.cooking_time.total_seconds() / 60, 1))


    def get_absolute_url(self):
        return reverse("lesson_detail", kwargs={'lesson_id':self.id})

    def __unicode__(self):
        return self.title
Пример #16
0
class Video(models.Model):
    id = models.AutoField(primary_key=True)
    # Retire, use description instead
    header = models.TextField(blank=True, null=True, max_length=2048)
    name = models.CharField(max_length=255)
    description = models.CharField(blank=True, null=True, max_length=2048)
    # Code for editors' internal use
    # production_code = models.CharField(null=True,max_length=255)
    categories = models.ManyToManyField(Category)
    editor = models.ForeignKey(User)
    has_tono_records = models.BooleanField(default=False)
    is_filler = models.BooleanField(default=False)  # Find a better name?
    publish_on_web = models.BooleanField(default=True)

    # disabled = models.BooleanField() # Not migrated
    # uploader = models.ForeignKey(User)
    # Planned duration in milliseconds, probably not going to be used
    # planned_duration = models.IntegerField()
    # Time when it is to be published on web
    # published_time = models.DateTimeField()

    proper_import = models.BooleanField(default=False)
    played_count_web = models.IntegerField(
        default=0, help_text='Number of times it has been played')
    created_time = models.DateTimeField(
        auto_now_add=True,
        null=True,
        help_text='Time the program record was created')
    updated_time = models.DateTimeField(
        auto_now=True,
        null=True,
        help_text='Time the program record has been updated')
    uploaded_time = models.DateTimeField(
        blank=True,
        null=True,
        help_text='Time the original video for the program was uploaded')
    framerate = models.IntegerField(
        default=25000,
        help_text='Framerate of master video in thousands / second')
    organization = models.ForeignKey(Organization,
                                     null=True,
                                     help_text='Organization for video')
    ref_url = models.CharField(blank=True,
                               max_length=1024,
                               help_text='URL for reference')
    duration = DurationField(blank=True, null=True)

    objects = VideoManager()

    class Meta:
        db_table = u'Video'
        get_latest_by = 'uploaded_time'

    def __unicode__(self):
        return self.name

    def is_public(self):
        return self.publish_on_web and self.proper_import

    def tags(self):
        tags = []
        if self.has_tono_records:
            tags.append("tono")
        if self.publish_on_web:
            tags.append("www")
        if self.is_filler:
            tags.append("filler")
        return ', '.join(tags)

    def videofiles(self):
        videofiles = VideoFile.objects.filter(video=self)
        return videofiles

    def category_list(self):
        categories = self.categories.filter(video=self)
        return categories

    def schedule(self):
        events = Scheduleitem.objects.filter(video=self)
        return events

    def first_broadcast(self):
        events = Scheduleitem.objects.filter(video=self)
        if events:
            return events[0]
        return None

    def last_broadcast(self):
        events = Scheduleitem.objects.filter(video=self)
        if events:
            return events[max(0, len(events) - 1)]
        return None

    def videofile_url(self, fsname):
        videofile = self.videofile_set.get(format__fsname=fsname)
        return videofile.location(relative=True)

    def small_thumbnail_url(self):
        format = FileFormat.objects.get(fsname="small_thumb")
        try:
            videofile = VideoFile.objects.get(video=self, format=format)
        except ObjectDoesNotExist:
            return "/static/default_small_thumbnail.png"
        return settings.FK_MEDIA_URLPREFIX + videofile.location(relative=True)

    def medium_thumbnail_url(self):
        format = FileFormat.objects.get(fsname="medium_thumb")
        try:
            videofile = VideoFile.objects.get(video=self, format=format)
        except ObjectDoesNotExist:
            return "/static/default_medium_thumbnail.png"
        return settings.FK_MEDIA_URLPREFIX + videofile.location(relative=True)

    def large_thumbnail_url(self):
        format = FileFormat.objects.get(fsname="large_thumb")
        try:
            videofile = VideoFile.objects.get(video=self, format=format)
        except ObjectDoesNotExist:
            return "/static/default_large_thumbnail.png"
        return settings.FK_MEDIA_URLPREFIX + videofile.location(relative=True)

    def old_id(self):
        format = FileFormat.objects.get(fsname="broadcast")
        videofile = VideoFile.objects.get(video=self, format=format)
        return videofile.old_filename.split('/')[0]

    def ogv_url(self):
        url = settings.FK_MEDIA_URLPREFIX + self.videofile_url("theora")
        return url

    def mp4_url(self):
        url = settings.FK_MEDIA_URLPREFIX + self.videofile_url("mp4")
        return url

    def get_absolute_url(self):
        return reverse('vod-video-detail', kwargs={'video_id': self.id})
Пример #17
0
class TestModel(models.Model):
    duration_field = DurationField()
Пример #18
0
class TestDefaultModel(models.Model):
    duration_field = DurationField(default=DEFAULT_DURATION)
Пример #19
0
class TestNullableModel(models.Model):
    duration_field = DurationField(null=True, blank=True)