class Produto(models.Model): nome = models.CharField('Produto', max_length=70) categoria = models.ForeignKey(Categoria, on_delete=models.PROTECT, related_name='categoria_produto', verbose_name='Categoria') recebido_por = CurrentUserField(on_delete=models.PROTECT, related_name='recebido_por', verbose_name='Recebido Por') fornecedor = models.ForeignKey(Fornecedores, on_delete=models.PROTECT, verbose_name='Fornecedor', related_name='fornecedo_produto') lote = models.CharField('Lote', max_length=50, null=True, blank=True) quantidade = models.IntegerField(default=1) data_recebimento = models.DateTimeField('Data Recebimento', auto_now=True) auterado_por = CurrentUserField(on_update=True) custo = models.DecimalField( max_digits=16, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], default=Decimal('0.00')) inf_adicionais = models.TextField('Informaçoes adiconais', null=True, blank=True) def __str__(self): return self.nome
class Authorable(models.Model): OWNERSHIP_FIELD = "creation_user" creation_datetime = models.DateTimeField(_("fecha de creación"), auto_now_add=True, blank=False, null=False, editable=False) modification_datetime = models.DateTimeField(_("fecha de modificación"), auto_now=True, blank=False, null=False, editable=False) creation_user = CurrentUserField( blank=True, verbose_name=_("usuario de creación"), on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_creations", ) modification_user = CurrentUserField( on_update=True, blank=True, verbose_name=_("usuario de modificación"), on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_modifications", ) class Meta: abstract = True
class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) create_user = CurrentUserField(editable=False, on_delete=models.SET(get_sentinel_user), related_name="create_user") updated_at = models.DateTimeField(auto_now=True) update_user = CurrentUserField(editable=False, on_delete=models.SET(get_sentinel_user), related_name="update_user") deleted_at = models.DateTimeField(null=True, editable=False) delete_user = models.ForeignKey( settings.AUTH_USER_MODEL, editable=False, null=True, on_delete=models.SET(get_sentinel_user), related_name="delete_user", ) def save(self, *args, **kwargs): logging.debug("save " + str(self.deleted_at)) self.update_user = get_current_authenticated_user() super(BaseModel, self).save(*args, **kwargs) def delete(self, *args, **kwargs): self.deleted_at = timezone.now() self.delete_user = get_current_authenticated_user() super(BaseModel, self).save(*args, **kwargs) class Meta: abstract = True
class Categoria(models.Model): nome = models.CharField('Nome', max_length=100) cadastrado_por = CurrentUserField(on_delete=models.PROTECT, related_name='criado_por') atualizado_por = CurrentUserField(on_update=True) cadastrado_em = models.DateTimeField('Cadastrado em', auto_now_add=True) modificado_em = models.DateTimeField('Modificado em', auto_now=True) def __str__(self): return self.nome
class Modelo(models.Model): modelo = models.CharField('Modelo', max_length=100) fabricante = models.CharField('Fabricante', max_length=100) cadastrado_por = CurrentUserField(on_delete=models.PROTECT, related_name='modelo_criado_por') cadastrado_em = models.DateTimeField('Cadastrado em', auto_now_add=True) modificado_em = models.DateTimeField('Modificado em', auto_now=True) atualizado_por = CurrentUserField(on_update=True) def __str__(self): return self.modelo
class UserMembership(models.Model): """ Roles """ code = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name=_('codice')) name = models.CharField(max_length=255, null=False, blank=False, verbose_name=_('nome')) description = models.TextField(max_length=500, null=True, blank=True, verbose_name=_('descrizione')) member = models.ForeignKey(to='AppUser', on_delete=models.CASCADE, verbose_name=_('utente'), default=None, blank=True, null=True) organization = models.ForeignKey(to='Organization', on_delete=models.CASCADE, verbose_name=_('ente'), default=None, blank=True, null=True) type = models.ForeignKey(to='MembershipType', on_delete=models.CASCADE, verbose_name=_('tipo'), default=None, blank=True, null=True) date_joined = models.DateTimeField(verbose_name=_('data creazione'), auto_now_add=True) date_updated = models.DateTimeField(verbose_name=_('data ultima modifica'), auto_now=True) created_by = CurrentUserField(verbose_name=_('creato da'), editable=False, related_name='%(class)s_created') updated_by = CurrentUserField(verbose_name=_('modificato da'), editable=False, related_name='%(class)s_updated') class Meta: unique_together = ('member', 'organization', 'type') verbose_name = _('ruolo') verbose_name_plural = _('ruoli') def __str__(self): return self.name
class Distribuicoes(models.Model): nome = models.CharField('Distribuição', max_length=100) pon = models.CharField('PON', max_length=10) cor = models.CharField('COR', max_length=20, null=True, blank=True) cadastrado_por = CurrentUserField(on_delete=models.PROTECT, related_name='distribuica_criado_por') cadastrado_em = models.DateTimeField('Cadastrado em', auto_now_add=True) modificado_em = models.DateTimeField('Modificado em', auto_now=True) atualizado_por = CurrentUserField(on_update=True) def __str__(self): return self.nome
class Cliente(models.Model): cliente = models.CharField('Cliente', max_length=30) cto = models.ForeignKey(CTO, on_delete=models.PROTECT, related_name='cliente_cto') cadastrado_por = CurrentUserField(on_delete=models.PROTECT, related_name='cliente_criado_por') cadastrado_em = models.DateTimeField('Cadastrado em', auto_now_add=True) modificado_em = models.DateTimeField('Modificado em', auto_now=True) atualizado_por = CurrentUserField(on_update=True) def __str__(self): return self.cliente
class AbstractDvzoModel(models.Model): create_user = CurrentUserField(related_name="created_%(class)ss") create_timestamp = models.DateTimeField(_("create_timestamp"), auto_now_add=True, null=True) update_user = CurrentUserField(on_update=True, related_name="updated_%(class)ss") update_timestamp = models.DateTimeField(_("update_timestamp"), auto_now=True, null=True) class Meta: abstract = True
class CTO(models.Model): nome = models.CharField('CTO', max_length=100) distribucao_cto = models.ForeignKey(Distribuicoes, on_delete=models.PROTECT, verbose_name='Distribuição', related_name='dist_cto') cor = models.CharField('COR', max_length=20, null=True, blank=True) cadastrado_por = CurrentUserField(on_delete=models.PROTECT, related_name='cto_criado_por') cadastrado_em = models.DateTimeField('Cadastrado em', auto_now_add=True) modificado_em = models.DateTimeField('Modificado em', auto_now=True) atualizado_por = CurrentUserField(on_update=True) def __str__(self): return self.nome
class SimpleModel(models.Model): model_name = NotImplemented url_name = 'home' url_params = tuple() def get_absolute_url(self): args = [self.__getattribute__(url_param) for url_param in self.url_params] return reverse(f'workouts:{self.url_name}', args =args) name = models.CharField(max_length=100) description = models.TextField(blank=True, default='') custom = models.BooleanField(default=True) climber = CurrentUserField() objects = SimpleModelManager() def __repr__(self): return f'{self.__class__.__name__}(' \ f'name={self.name},' \ f'custom={self.custom},' \ f'climber={self.climber},' def __str__(self) -> str: return f'{self.name}' class Meta: abstract = True unique_together = (('name', 'climber')) get_latest_by = ('updated',)
class Application(models.Model): user = CurrentUserField() company = models.ForeignKey(Companies, on_delete=models.CASCADE) def __str__(self): student = Student.objects.get(user=self.user) return str(student)
class Movimiento(models.Model): usuario = CurrentUserField(related_name="movimiento_usuario") tipo = models.ForeignKey(Tipo, verbose_name="Tipo movimiento", related_name="movimiento_tipo", on_delete=models.CASCADE, blank=False, null=False) cantidad = models.DecimalField(decimal_places=2, max_digits=12, validators=[ MaxValueValidator( Decimal('100000000000.00')), MinValueValidator(Decimal('0.00')) ]) descripcion = models.CharField(max_length=30, verbose_name="Descripción", blank=False, null=False) fecha_inscripcion = models.DateTimeField(auto_now_add=True) @staticmethod def obtener_suma_movimientos(id_usuario, tipo): from django.db.models import Sum movimiento = Movimiento.objects.filter( tipo__nombre=tipo, usuario__pk=id_usuario).aggregate(total=Sum('cantidad')) if movimiento['total']: return movimiento['total'] else: return 0
class RamoAtividade(models.Model): atividade = models.CharField( max_length=80, help_text= 'Informe o Ramo de Atividade. (exemplo: alimentação, vestuário, restaurante, etc.)' ) dataCadastro = models.DateTimeField( verbose_name=u'Cadastrado em', auto_now_add=True, editable=False) #nao vai aparecer na tela CadastradoPor = CurrentUserField(verbose_name=u'Cadastrado Por', editable=False) # DataAlteracao = models.DateTimeField(verbose_name=u'Alterado em', auto_now_add=True) #nao vai aparecer na tela # AlteradoPor_Id = models.ForeignKey(User, blank=False, related_name='Cadastrado_por', editable=False, default=current_user.get_current_user) ativo = models.BooleanField(default=True) exclude = ('ativo') class Meta: ordering = ['atividade'] verbose_name = (u'ramo de Atividade') verbose_name_plural = (u'ramos de Atividades') def __str__(self): """ String representando o Model object (in Admin site etc.) """ return self.atividade
class Item(models.Model): slug = models.CharField(max_length=32, blank=True, editable=False) created_by = CurrentUserField() created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) title = models.CharField(max_length=32, default="", help_text="Item Title") info = models.TextField(help_text="Extra information about this item.") price = models.DecimalField(max_digits=8, decimal_places=2, help_text="Price (USD)") item_img = models.ImageField(upload_to='') def __str__(self): return f"{self.title} (#{self.pk})" def get_absolute_url(self): """ Returns path for a listing """ path_components = {'slug': self.slug} return reverse('show_item', kwargs=path_components) def save(self, *args, **kwargs): """ Creates slug automatically when a listing is created """ if not self.pk: self.slug = slugify( f"{self.title} {''.join(choice(ascii_letters + digits) for _ in range(3))}", allow_unicode=True) return super(Item, self).save(*args, **kwargs)
class Cupom(models.Model): user = models.ForeignKey(User, related_name='rel_cupom_participante', on_delete=models.PROTECT) documentoFiscal = models.ForeignKey(DocumentoFiscal, related_name='rel_cupom_doc', null=False, blank=False, default=1, on_delete=models.PROTECT) operador = CurrentUserField(verbose_name=u'Cadastrado Por', related_name='rel_cupom_operador', editable=False) dataCriacao = models.DateTimeField(verbose_name=u'Cadastrado em', auto_now_add=True, editable=False) impresso = models.BooleanField(default=False) dataImpressao = models.DateTimeField(null=True) def __str__(self): return 'Cupom número: {}'.format(self.id) def get_absolute_url(self): return reverse('cupom:details', args=[str(self.numeroCupom)]) def get_info(self): return 'Participante: {} CPF:{} Celular {} Documento Fiscal: {} Operador: {} Data de impressão: {} Data da compra: {} vendedor: {} '.format( self.user.profile.nome, self.user.profile.CPF, self.user.profile.foneCelular1, self.documentoFiscal.numeroDocumento, self.operador.username, self.dataImpressao, self.documentoFiscal.dataDocumento, self.documentoFiscal.vendedor)
class Generic(models.Model): class Meta: abstract = True created_time = models.DateTimeField(_("created at"), auto_now_add=True, editable=False) updated_time = models.DateTimeField(_("updated"), auto_now=True, editable=False, null=True, blank=True) created_by = CurrentUserField(related_name="+", editable=False) updated_by = CurrentUserField(on_update=True, related_name="+", editable=False)
class Project(models.Model): project_id = models.AutoField(primary_key=True) name = models.CharField(max_length=256, unique=True, blank=False) created = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=10000, default='') slug = models.SlugField(max_length=256, unique=True) created_by = CurrentUserField() def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) return super().save(*args, **kwargs) def get_absolute_url(self): return reverse('project_detail', kwargs={'slug': self.slug}) @property def id(self): return f'P{self.pk}' @property def path(self): path = DATALAKE_ROOT / 'P' / self.id return path @property def path_exists(self): return self.path.is_dir()
class Post(models.Model): text = models.CharField(max_length=200) posted_by = CurrentUserField(related_name='posted_by') pub_date = models.DateTimeField('Publication Date', auto_now=True) image = models.ImageField(upload_to='post-images', null=True) in_reply_to_post = models.IntegerField(null=True) def get_readable_date(self): return self.pub_date.strftime("%B %d, %Y") def get_post_belongs_to_authenticated_user(self): return self.posted_by.pk == get_current_authenticated_user().pk def get_user(self): user_dict = vars(self.posted_by) return {"id": user_dict["id"], "username": user_dict["username"]} def get_likes_count(self): return PostRate.objects.filter(liked=True, rated_post=self).count() def get_dislikes_count(self): return PostRate.objects.filter(liked=False, rated_post=self).count() def get_comments(self): return Post.objects.filter(in_reply_to_post=self.pk) def get_comments_count(self): return Post.objects.filter(in_reply_to_post=self.pk).count() def __str__(self): return str(self)
class Project(models.Model): project_id = models.AutoField(primary_key=True) name = models.CharField(max_length=256, unique=True, blank=False) created = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=10000, default="") slug = models.SlugField(max_length=256, unique=True) created_by = CurrentUserField(related_name="creator") users = models.ManyToManyField(User, related_name="users", blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) return super().save(*args, **kwargs) @property def url(self): return reverse_lazy("project:detail", kwargs={"slug": self.slug}) @property def id(self): return f"P{self.pk}" @property def path(self): path = DATALAKE_ROOT / "P" / self.id return path @property def path_exists(self): return self.path.is_dir()
class DinnerOrder(models.Model): user = CurrentUserField() room = models.ForeignKey(Room, null=True, on_delete=models.SET_NULL) starter = models.ForeignKey(Starter, blank=True, null=True, on_delete=models.SET_NULL) main = models.ForeignKey(Main, blank=True, null=True, on_delete=models.SET_NULL) dessert = models.ForeignKey(Dessert, blank=True, null=True, on_delete=models.SET_NULL) ordered_date = models.DateTimeField(auto_now_add=True, null=True) updated_date = models.DateTimeField(auto_now=True, null=True) delivery_time = models.DateTimeField(blank=True, null=True) comment = models.CharField(max_length=200, blank=True, null=True) status = models.CharField(max_length=20, choices=ORDER_STATUS, default='pending') def __str__(self): return str(self.room)
class CVModel(models.Model): created_by = CurrentUserField(default=get_current_authenticated_user, blank=False) date = models.DateTimeField(default=datetime.now, blank=False) position = models.CharField(max_length=128, blank=False) salary = models.PositiveIntegerField(blank=False, null=False) personal_info = models.TextField() skills = models.TextField() french = 'french' english = 'english' german = 'german' LANGUAGE = [ (french, 'Французский'), (english, 'Английский'), (german, 'Немецкий'), ] selected_language = models.CharField( max_length=32, choices=LANGUAGE, default=english, ) def get_absolute_url(self): return reverse('cv_update', args=(self.id, ))
class Product_Price(models.Model): user = CurrentUserField() Product_Name = models.CharField(max_length=200, blank=True, null=True) Product_price = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
class VendorsCustomer(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) user = CurrentUserField() institution_name = models.CharField(max_length=200, blank=True, verbose_name="Instituion Name") institution_id = models.CharField(max_length=200, blank=True, verbose_name="Instituion ID") address = models.CharField(max_length=500, verbose_name="Address", blank=True) contact = models.CharField(verbose_name="Contact", max_length=20, blank=True, default='N/A') profile_Image = models.ImageField( verbose_name="Profile Image", upload_to='Vendor_Customer_Profile_Pic/', default= 'https://icon-library.net/images/young-person-icon/young-person-icon-7.jpg', blank=True) gender = models.CharField(verbose_name="Gender", max_length=2, choices=GENDER_CHOICES, blank=False, default='M') Created_at = models.DateTimeField(auto_now_add=True) Updated_at = models.DateTimeField(auto_now=True)
class Delivery(models.Model): user = CurrentUserField() order = models.ForeignKey(Order, on_delete=models.CASCADE) courier_name = models.CharField(max_length=120) created_date = models.DateField(auto_now_add=True) def __str__(self): return self.courier_name
class Product(models.Model): user = CurrentUserField() name = models.CharField(max_length=120, unique=True) quantity = models.PositiveIntegerField() created_date = models.DateField(auto_now_add=True) def __str__(self): return self.name
class HolidayRequest(models.Model): class Meta(object): verbose_name = u"Demande d'absence" verbose_name_plural = u"Demandes d'absence" constraints = [ models.UniqueConstraint(fields=['employee', 'start_date', 'end_date'], name='unique holiday request') ] REASONS = [ (1, u'Congés'), (2, u'Maladie'), (3, u'Formation'), (4, u'Desiderata') ] request_accepted = models.BooleanField(u"Demande acceptée", default=False, blank=True) validated_by = models.ForeignKey('invoices.Employee', related_name='validator', on_delete=models.CASCADE, blank=True, null=True) employee = CurrentUserField() start_date = models.DateField(u'Date début') end_date = models.DateField(u'Date fin') half_day = models.BooleanField(u"Demi journée") reason = models.PositiveSmallIntegerField( choices=REASONS) def clean(self, *args, **kwargs): exclude = [] super(HolidayRequest, self).clean_fields(exclude) messages = self.validate(self.id, self.__dict__) if messages: raise ValidationError(messages) @staticmethod def validate(instance_id, data): result = {} result.update(HolidayRequest.validate_dates(data)) result.update(validate_date_range(instance_id, data)) result.update(validate_date_range_vs_timesheet(instance_id, data)) return result @staticmethod def validate_dates(data): messages = {} is_valid = data['end_date'] is None or data['start_date'] <= data['end_date'] if not is_valid: messages = {'end_date': 'End date must be bigger than Start date'} return messages def get_admin_url(self): info = (self._meta.app_label, self._meta.model_name) return reverse('admin:%s_%s_change' % info, args=(self.pk,)) def __str__(self): return u'%s - %s du %s au %s' % ( self.employee, self.REASONS[self.reason - 1][1], self.start_date, self.end_date)
class Connection(models.Model): vaccine = models.ForeignKey('Vaccine', on_delete=models.CASCADE, verbose_name='Szczepionka') branch = models.ForeignKey('Branch', on_delete=models.CASCADE, verbose_name='Placówka') date = models.DateField(auto_now=True, editable=False) amount = models.IntegerField(default=0, verbose_name='Ilość') modified_by = CurrentUserField() def __str__(self): return self.vaccine.name + ' w oddziale ' + self.branch.name
class TaskFeedback(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, null=True, blank=True) sender = CurrentUserField() is_solved = models.BooleanField() feedback_content = models.TextField(max_length=1000, null=True, blank=True) date_added = models.DateTimeField(auto_now_add = True) def __str__(self): return self.feedback_content
class Demande(models.Model): urgenceChoix = [ ('A Exécuter Immediatement', 'A Exécuter Immediatement'), ('A Exécuter Dans Les Plus Brefs Délais', 'A Exécuter Dans Les Plus Brefs Délais'), ('Peut Etre Reporté', 'Peut Etre Reporté'), ] num_releve = models.CharField( max_length=20, verbose_name='Numéro de relevé') created_by = CurrentUserField(verbose_name='Nom du demandeur') chauffeur = models.ForeignKey(Chauffeur, on_delete=models.CASCADE) code_vehicule = models.CharField( null=True, max_length=50, verbose_name='Code véhicule') code_remorque = models.CharField( max_length=50, verbose_name='Code remorque') imat_vehicule = models.CharField( max_length=50, verbose_name='Imat. véhicule') imat_remorque = models.CharField( max_length=50, verbose_name='Imat. Remorque') date_frais = models.DateField(verbose_name='Date de frais') date_demande = models.DateField( auto_now_add=True, verbose_name='Date de demande') # code activite analytique code_activite = models.CharField( max_length=150, choices=codeActivite, verbose_name='Code Activité') libelle_activite = models.CharField( max_length=255, choices=directionActChoix, verbose_name='Libelle') quantite = models.IntegerField(default=1) pu = models.FloatField(default=0.00, verbose_name='Prix unitaire') total = models.FloatField() urgence = models.CharField(choices=urgenceChoix, max_length=255) traite = models.BooleanField(default=False, verbose_name='Validé') motif = models.ForeignKey( Motif, verbose_name="MOTIF", on_delete=models.CASCADE, default="") # les autres element de l'analytique agence = models.CharField(choices=agenceChoix, max_length=255) a_rembourser = models.BooleanField(default=False) axe_analyse = models.CharField(choices=axeAnalyseChoix, max_length=255) def get_total_prix(self): return self.quantite * self.pu def save_model(self, request, obj, form, change): obj.created_by = request.user super().save_model(request, obj, form, change) def get_detail_url(self): return f"traitement/{self.id}" def __str__(self): return f"{self.id} - {self.created_by}" class Meta: ordering = ("-date_demande", "libelle_activite")