class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Charge", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("stripe_id", models.CharField(max_length=255, unique=True)), ("amount", models.IntegerField()), ("amount_refunded", models.IntegerField()), ("balance_transaction", models.CharField(max_length=255)), ("captured", models.BooleanField(default=False)), ("created", models.DateTimeField()), ( "currency", models.CharField(choices=[("usd", "usd")], default="usd", max_length=3), ), ("dispute", models.BooleanField(default=False)), ("livemode", models.BooleanField(default=False)), ("paid", models.BooleanField(blank=True, null=True)), ( "receipt_email", models.CharField(blank=True, default="", max_length=800), ), ("refunded", models.BooleanField(default=False)), ( "status", models.CharField( choices=[ ("succeeded", "succeeded"), ("pending", "pending"), ("failed", "failed"), ], default="pending", max_length=9, ), ), ], ), migrations.CreateModel( name="Customer", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("stripe_id", models.CharField(max_length=255, unique=True)), ("livemode", models.BooleanField(default=False)), ( "account_balance", models.DecimalField(blank=True, decimal_places=2, max_digits=9, null=True), ), ( "currency", models.CharField(choices=[("usd", "usd")], default="usd", max_length=3), ), ("delinquent", models.BooleanField(default=False)), ("default_source", models.TextField(blank=True, null=True)), ("metadata", django.contrib.postgres.fields.jsonb.JSONField()), ], ), migrations.CreateModel( name="Event", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("stripe_id", models.CharField(max_length=255, unique=True)), ("created", models.DateTimeField()), ("data", django.contrib.postgres.fields.jsonb.JSONField()), ("livemode", models.BooleanField(default=False)), ("request", models.CharField(max_length=255)), ("kind", models.CharField(max_length=64)), ("metadata", django.contrib.postgres.fields.jsonb.JSONField()), ], ), migrations.CreateModel( name="Invoice", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("stripe_id", models.CharField(max_length=255, unique=True)), ("attempt_count", models.IntegerField()), ("attempted", models.BooleanField(default=False)), ( "currency", models.CharField(choices=[("usd", "usd")], default="usd", max_length=3), ), ("description", models.TextField(blank=True)), ("ending_balance", models.IntegerField(null=True)), ("forgiven", models.BooleanField(default=False)), ( "hosted_invoice_url", models.CharField(blank=True, default="", max_length=799), ), ( "invoice_pdf", models.CharField(blank=True, default="", max_length=799), ), ("livemode", models.BooleanField(default=False)), ("paid", models.BooleanField(default=False)), ("period_end", models.DateTimeField()), ("period_start", models.DateTimeField()), ("receipt_number", models.CharField(max_length=64, null=True)), ("starting_balance", models.IntegerField()), ( "statement_descriptor", models.CharField(blank=True, default="", max_length=22), ), ( "subscription_proration_date", models.DateTimeField(blank=True, null=True), ), ("subtotal", models.IntegerField(blank=True, null=True)), ("tax", models.IntegerField(blank=True, null=True)), ( "tax_percent", models.DecimalField(decimal_places=2, max_digits=5, null=True), ), ("total", models.IntegerField()), ], ), migrations.CreateModel( name="Plan", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("stripe_id", models.CharField(max_length=255, unique=True)), ("active", models.BooleanField(default=False)), ( "aggregate_usage", models.CharField( choices=[ ("sum", "sum"), ("last_during_period", "last_during_period"), ("max", "max"), ("last_ever", "LAST_EVER"), ], default="sum", max_length=18, null=True, ), ), ("amount", models.IntegerField()), ("created", models.DateTimeField(blank=True, null=True)), ( "currency", models.CharField(choices=[("usd", "usd")], default="usd", max_length=3), ), ( "interval", models.CharField( choices=[ ("day", "day"), ("week", "week"), ("month", "month"), ("year", "year"), ], default="month", max_length=5, ), ), ("livemode", models.BooleanField(default=False)), ("metadata", django.contrib.postgres.fields.jsonb.JSONField()), ("nickname", models.CharField(max_length=255)), ("trial_period_days", models.IntegerField(default=0, null=True)), ( "usage_type", models.CharField( choices=[("licensed", "licensed"), ("metered", "metered")], max_length=8, ), ), ], ), migrations.CreateModel( name="Product", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("stripe_id", models.CharField(max_length=255, unique=True)), ("name", models.CharField(max_length=255)), ("metadata", django.contrib.postgres.fields.jsonb.JSONField()), ], ), migrations.CreateModel( name="Subscription", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("stripe_id", models.CharField(max_length=255, unique=True)), ("livemode", models.BooleanField(default=False)), ("metadata", django.contrib.postgres.fields.jsonb.JSONField()), ("cancel_at_period_end", models.BooleanField(default=False, null=True)), ("current_period_start", models.DateTimeField(blank=True, null=True)), ("current_period_end", models.DateTimeField(blank=True, null=True)), ("canceled_at", models.DateTimeField(blank=True, null=True)), ("ended_at", models.DateTimeField(blank=True, null=True)), ( "customer", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="subscriptions", to="billing.Customer", ), ), ( "plans", models.ManyToManyField(related_name="subscriptions", to="billing.Plan"), ), ], ), migrations.CreateModel( name="SubscriptionItem", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("stripe_id", models.CharField(max_length=255, unique=True)), ("livemode", models.BooleanField(default=False)), ("created", models.DateTimeField()), ( "plan", models.ForeignKey( on_delete=django.db.models.deletion.PROTECT, related_name="subscription_items", to="billing.Plan", ), ), ( "subscription", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="subscription_items", to="billing.Subscription", ), ), ], ), migrations.CreateModel( name="UsageRecord", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("stripe_id", models.CharField(max_length=255, unique=True)), ("livemode", models.BooleanField(default=False)), ( "action", models.CharField( choices=[("increment", "increment"), ("set", "set")], default="increment", max_length=9, ), ), ("quantity", models.IntegerField(default=0)), ("timestamp", models.DateTimeField()), ( "subscription_item", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="usage_records", to="billing.SubscriptionItem", ), ), ], ), ]
class ChoicesModel(models.Model): choices_field_with_nonstandard_args = models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES, verbose_name='A label')
class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name='Date', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date', models.DateField(help_text=b'Format: MM/DD/YYYY')), ], ), migrations.CreateModel( name='Disease', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(help_text=b'', max_length=200)), ], ), migrations.CreateModel( name='Disease_Entry', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('susceptibility', models.DecimalField( help_text= b'Format: 5.00, Percentage of susceptibility of this variety to this disease.', max_digits=8, decimal_places=5)), ('disease', models.ForeignKey(help_text=b'Name of disease', to='variety_trials_data.Disease')), ], ), migrations.CreateModel( name='Location', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(help_text=b'', max_length=200)), ('latitude', models.DecimalField( help_text= b'Format: 46.8772, Overrides the latitude value derived from the zipcode. The Equator is 0, south is negative.', null=True, max_digits=13, decimal_places=10, blank=True)), ('longitude', models.DecimalField( help_text= b'Format: -96.7894, Overrides the longitude value derived from the zipcode. The Grand Meridian is 0, west is negative.', null=True, max_digits=13, decimal_places=10, blank=True)), ], ), migrations.CreateModel( name='Location_Year_PlantingMethods_Survey_Answer', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('year', models.PositiveIntegerField()), ('irrigated', models.CharField(max_length=32)), ('fungicide', models.CharField(max_length=32)), ('notes', models.CharField(max_length=2000)), ('location', models.ForeignKey(to='variety_trials_data.Location')), ], ), migrations.CreateModel( name='Trial_Entry', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('bushels_acre', models.DecimalField( help_text=b'Format: 37.4, Bushels per Acre', max_digits=10, decimal_places=5)), ('protein_percent', models.DecimalField( help_text=b'Format: 12.1, Percentage of protein per pound', null=True, max_digits=8, decimal_places=5, blank=True)), ('test_weight', models.DecimalField( help_text=b'Format: 50.1, Pounds per bushel', null=True, max_digits=10, decimal_places=5, blank=True)), ('kernel_weight', models.DecimalField( help_text=b'Format: 30.5, Grams per 1000 kernels', null=True, max_digits=10, decimal_places=5, blank=True)), ('plant_height', models.DecimalField( help_text=b'Format: 24.5, Height of plant in inches', null=True, max_digits=10, decimal_places=5, blank=True)), ('days_to_head', models.DecimalField( help_text=b'Format: 57, Days from planting to head', null=True, max_digits=8, decimal_places=5, blank=True)), ('lodging_factor', models.DecimalField( help_text= b'Format: 4, Ranking: 1 (No Lodging) to 9 (Heavy Lodging)', null=True, max_digits=8, decimal_places=5, blank=True)), ('jday_of_head', models.DecimalField( help_text=b'Format: 265, Julian day of head', null=True, max_digits=8, decimal_places=5, blank=True)), ('winter_survival_rate', models.DecimalField( help_text=b'Format: 20.5, Percentage that survive winter', null=True, max_digits=8, decimal_places=5, blank=True)), ('shatter', models.DecimalField( help_text= b'Format 4, Ranking: 1 (Least Shatter) to 9 (Most Shatter)', null=True, max_digits=8, decimal_places=5, blank=True)), ('seeds_per_round', models.DecimalField( help_text= b'Format: 1.2, Number of seeds (in 1000s) per round', null=True, max_digits=8, decimal_places=5, blank=True)), ('canopy_density', models.DecimalField( help_text= b'Format 4, Ranking: 1 (Least Dense) to 9 (Most Dense)', null=True, max_digits=8, decimal_places=5, blank=True)), ('canopy_height', models.DecimalField( help_text=b'Format: 26.2, Height of canopy in inches', null=True, max_digits=10, decimal_places=5, blank=True)), ('days_to_flower', models.DecimalField( help_text=b'Format: 28, Days from planting to flower', null=True, max_digits=8, decimal_places=5, blank=True)), ('seed_oil_percent', models.DecimalField( help_text=b'Format: 5.6, Percentage of mass', null=True, max_digits=10, decimal_places=5, blank=True)), ('planting_method_tags', models.CharField( help_text=b'Comma-separated list of planting methods', max_length=200, null=True, blank=True)), ('seeding_rate', models.DecimalField( help_text= b'Format: 2.1, Number of seeds (in 1000s) per foot', null=True, max_digits=8, decimal_places=5, blank=True)), ('previous_crop', models.CharField( help_text=b'Name of the previous crop at this location', max_length=200, null=True, blank=True)), ('moisture_basis', models.DecimalField( help_text=b'Format: 3, Ranking: 1 (Dry) to 9 (Flooded)', null=True, max_digits=10, decimal_places=5, blank=True)), ('lsd_05', models.DecimalField( help_text= b'Bushels per Acre LSD at a=0.05 (for the entire location in this year)', null=True, max_digits=10, decimal_places=5, blank=True)), ('lsd_10', models.DecimalField( help_text= b'Bushels per Acre LSD at a=0.10 (for the entire location in this year)', null=True, max_digits=10, decimal_places=5, blank=True)), ('hsd_10', models.DecimalField( help_text= b'Bushels per Acre HSD at a=0.05 (for the entire location in this year)', null=True, max_digits=10, decimal_places=5, blank=True)), ('hidden', models.BooleanField(default=True, help_text=b'')), ('harvest_date', models.ForeignKey( related_name='harvest_date', to='variety_trials_data.Date', help_text=b'Date this trial was harvested')), ('location', models.ForeignKey(help_text=b'Name of location', to='variety_trials_data.Location')), ('plant_date', models.ForeignKey(related_name='plant_date', blank=True, to='variety_trials_data.Date', help_text=b'Date this trial was planted', null=True)), ], ), migrations.CreateModel( name='Trial_Entry_History', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('username', models.CharField(max_length=200)), ('created_date', models.DateField()), ('trial_entry', models.ForeignKey( to='variety_trials_data.Trial_Entry', on_delete=django.db.models.deletion.DO_NOTHING)), ], ), migrations.CreateModel( name='Variety', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(help_text=b'', max_length=200)), ('description_url', models.CharField( help_text= b'A link to a resource that describes this variety.', max_length=200, null=True, blank=True)), ('picture_url', models.CharField( help_text=b'A link to a small picture of this variety.', max_length=200, null=True, blank=True)), ('agent_origin', models.CharField(help_text=b'The name of the cultivar.', max_length=200, null=True, blank=True)), ('year_released', models.CharField( help_text= b'Format: YYYY, The year this variety was released.', max_length=200, null=True, blank=True)), ('straw_length', models.CharField(help_text=b'The length of the stems.', max_length=200, null=True, blank=True)), ('maturity', models.CharField(help_text=b'Type of maturity(?)', max_length=200, null=True, blank=True)), ('grain_color', models.CharField(help_text=b'Color of mature grain.', max_length=200, null=True, blank=True)), ('seed_color', models.CharField(help_text=b'Color of seed.', max_length=200, null=True, blank=True)), ('beard', models.CharField(help_text=b'Color (?) of beard.', max_length=200, null=True, blank=True)), ('wilt', models.CharField(help_text=b'Degree of wilt(?)', max_length=200, null=True, blank=True)), ], options={ 'ordering': ['-name'], }, ), migrations.CreateModel( name='Zipcode', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('zipcode', models.PositiveIntegerField()), ('city', models.CharField(max_length=200)), ('state', models.CharField(max_length=2)), ('latitude', models.DecimalField(max_digits=13, decimal_places=10)), ('longitude', models.DecimalField(max_digits=13, decimal_places=10)), ('timezone', models.SmallIntegerField()), ('daylight_savings', models.SmallIntegerField()), ], ), migrations.CreateModel( name='VarietyManager', fields=[ ('variety_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='variety_trials_data.Variety')), ], bases=('variety_trials_data.variety', ), ), migrations.AddField( model_name='variety', name='diseases', field=models.ManyToManyField( to='variety_trials_data.Disease', null=True, through='variety_trials_data.Disease_Entry', blank=True), ), migrations.AddField( model_name='trial_entry', name='variety', field=models.ForeignKey(help_text=b'Name of variety', to='variety_trials_data.Variety'), ), migrations.AddField( model_name='location', name='zipcode', field=models.ForeignKey( help_text= b'Format: 12345, The five-digit zipcode of this locaton.', to='variety_trials_data.Zipcode'), ), migrations.AddField( model_name='disease_entry', name='variety', field=models.ForeignKey(help_text=b'Name of variety', to='variety_trials_data.Variety'), ), ]
class Payment(models.Model): class STATUS: PROCESSED = 'processed' SUCCESS = 'success' FAIL = 'fail' CHOICES = ( (PROCESSED, 'Processed'), (SUCCESS, 'Success'), (FAIL, 'Fail'), ) class PAYMENT_TYPE: PC = 'pc' AC = 'ac' GP = 'gp' MC = 'mc' WM = 'wm' SB = 'sb' AB = 'ab' CHOICES = ( (PC, 'Яндекс.Деньги'), (AC, 'Банковская карта'), (GP, 'По коду через терминал'), (MC, 'Со счета мобильного телефона'), (WM, 'WebMoney'), (SB, 'Выставление счета в Сбербанк.Онлайн'), (AB, 'Выставление счета в АльфаКлик'), ) class CURRENCY: RUB = 643 TEST = 10643 CHOICES = ( (RUB, 'Рубли'), (TEST, 'Тестовая валюта'), ) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, verbose_name='Пользователь') pub_date = models.DateTimeField('Время создания', auto_now_add=True) # Required request fields shop_id = models.PositiveIntegerField( 'ID магазина', default=settings.YANDEX_MONEY_SHOP_ID) scid = models.PositiveIntegerField('Номер витрины', default=settings.YANDEX_MONEY_SCID) customer_number = models.CharField( 'Идентификатор плательщика', max_length=64, default=lambda: str(uuid4()).replace('-', '')) order_amount = models.DecimalField('Сумма заказа', max_digits=15, decimal_places=2) # Non-required fields article_id = models.PositiveIntegerField('Идентификатор товара', blank=True, null=True) payment_type = models.CharField('Способ платежа', max_length=2, default=PAYMENT_TYPE.PC, choices=PAYMENT_TYPE.CHOICES) order_number = models.CharField( 'Номер заказа', max_length=64, default=lambda: str(uuid4()).replace('-', '')) cps_email = models.EmailField('Email плательщика', max_length=100, blank=True, null=True) cps_phone = models.CharField('Телефон плательщика', max_length=15, blank=True, null=True) success_url = models.URLField('URL успешной оплаты', default=settings.YANDEX_MONEY_SUCCESS_URL) fail_url = models.URLField('URL неуспешной оплаты', default=settings.YANDEX_MONEY_FAIL_URL) # Transaction info status = models.CharField('Статус', max_length=16, choices=STATUS.CHOICES, default=STATUS.PROCESSED) invoice_id = models.PositiveIntegerField('Номер транзакции оператора', blank=True, null=True) shop_amount = models.DecimalField( 'Сумма полученная на р/с', max_digits=15, decimal_places=2, blank=True, null=True, help_text='За вычетом процента оператора') order_currency = models.PositiveIntegerField('Валюта', default=CURRENCY.RUB, choices=CURRENCY.CHOICES) shop_currency = models.PositiveIntegerField('Валюта полученная на р/с', blank=True, null=True, default=CURRENCY.RUB, choices=CURRENCY.CHOICES) performed_datetime = models.DateTimeField('Время выполнение запроса', blank=True, null=True) @property def is_payed(self): return self.status == self.STATUS.SUCCESS def send_signals(self): status = self.status if status == self.STATUS.PROCESSED: payment_process.send(sender=self) if status == self.STATUS.SUCCESS: payment_completed.send(sender=self) class Meta: ordering = ('-pub_date', ) unique_together = (('shop_id', 'order_number'), ) verbose_name = 'Платёж' verbose_name_plural = 'Платежи' app_label = 'yandex_money'
class Migration(migrations.Migration): initial = True dependencies = [ ('core', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Ingredient', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=300, null=True, unique=True)), ('use_count', models.PositiveIntegerField(default=0)), ], options={ 'verbose_name': 'Ingredient', 'verbose_name_plural': 'Ingredients', }, ), migrations.CreateModel( name='IngredientAmount', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('amount', models.DecimalField( decimal_places=2, default=Decimal('1'), max_digits=12, validators=[ django.core.validators.MinValueValidator( Decimal('0.00')) ], verbose_name='Amount')), ('ingredient', models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='ingredient_amounts', to='recipe.Ingredient')), ], ), migrations.CreateModel( name='Unit', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=60, unique=True, verbose_name='Name')), ('name_abbrev', models.CharField(blank=True, max_length=60, verbose_name='Abbreviation')), ('plural_abbrev', models.CharField(blank=True, max_length=60, verbose_name='Plural Abbreviation')), ('type', models.IntegerField( choices=[(0, 'Other'), (1, 'Mass'), (2, 'Volume')])), ('system', models.IntegerField(choices=[(0, 'Metric'), (1, 'Imperial')], null=True)), ], options={ 'verbose_name': 'Unit', 'verbose_name_plural': 'Units', 'ordering': ['name'], }, ), migrations.CreateModel( name='Recipe', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True, null=True)), ('modified_at', models.DateTimeField(auto_now=True, null=True)), ('name', models.CharField(max_length=500, unique=True)), ('short_description', models.TextField(default='')), ('description', tinymce.models.HTMLField(default='', verbose_name='Text')), ('prep_time', models.PositiveSmallIntegerField(blank=True, null=True)), ('cook_time', models.PositiveSmallIntegerField(blank=True, null=True)), ('large_image_url', models.URLField(default='https://via.placeholder.com/1000', max_length=300)), ('med_image_url', models.URLField(default='https://via.placeholder.com/400', max_length=300)), ('sm_image_url', models.URLField(default='https://via.placeholder.com/150', max_length=300)), ('servings', models.PositiveSmallIntegerField(default=1)), ('max_servings', models.PositiveSmallIntegerField(default=25)), ('is_published', models.BooleanField(default=False)), ('slug', models.SlugField(max_length=100)), ('likes', models.PositiveSmallIntegerField(default=1)), ('author', models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)), ('image', models.OneToOneField( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.PublicImage')), ('ingredients', models.ManyToManyField(blank=True, through='recipe.IngredientAmount', to='recipe.Ingredient')), ('series', models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='recipes', to='core.Series')), ('tags', taggit.managers.TaggableManager( blank=True, help_text='A comma-separated list of tags.', through='core.TaggedWhatever', to='core.BasicTag', verbose_name='Tags')), ], options={ 'verbose_name': 'Recipe', 'verbose_name_plural': 'Recipes', 'ordering': ['name'], }, ), migrations.AddField( model_name='ingredientamount', name='recipe', field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='ingredient_amounts', to='recipe.Recipe'), ), migrations.AddField( model_name='ingredientamount', name='unit', field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='ingredient_amounts', to='recipe.Unit'), ), migrations.CreateModel( name='Direction', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='', max_length=100)), ('text', tinymce.models.HTMLField(default='', verbose_name='Text')), ('direction_order', models.PositiveIntegerField(db_index=True, default=0, editable=False)), ('ingredient_amounts', models.ManyToManyField(blank=True, to='recipe.IngredientAmount')), ('recipe', adminsortable.fields.SortableForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name='directions', to='recipe.Recipe')), ], options={ 'verbose_name': 'Direction', 'verbose_name_plural': 'Directions', 'ordering': ['direction_order'], }, ), migrations.AddConstraint( model_name='ingredientamount', constraint=models.CheckConstraint( check=models.Q(amount__gte=Decimal('0')), name='amount_gte_0'), ), migrations.AddConstraint( model_name='ingredientamount', constraint=models.UniqueConstraint( fields=('recipe', 'ingredient'), name='no_duplicate_ingredients_in_recipe'), ), migrations.AddConstraint( model_name='direction', constraint=models.UniqueConstraint( fields=('recipe', 'text'), name='no duplicate direction per recipe'), ), ]
class Checkout(ModelWithMetadata): """A shopping checkout.""" created_at = models.DateTimeField(auto_now_add=True) last_change = models.DateTimeField(auto_now=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, related_name="checkouts", on_delete=models.CASCADE, ) email = models.EmailField(blank=True, null=True) token = models.UUIDField(primary_key=True, default=uuid4, editable=False) channel = models.ForeignKey( Channel, related_name="checkouts", on_delete=models.PROTECT, ) billing_address = models.ForeignKey( "account.Address", related_name="+", editable=False, null=True, on_delete=models.SET_NULL, ) shipping_address = models.ForeignKey( "account.Address", related_name="+", editable=False, null=True, on_delete=models.SET_NULL, ) shipping_method = models.ForeignKey( ShippingMethod, blank=True, null=True, related_name="checkouts", on_delete=models.SET_NULL, ) collection_point = models.ForeignKey( "warehouse.Warehouse", blank=True, null=True, related_name="checkouts", on_delete=models.SET_NULL, ) note = models.TextField(blank=True, default="") currency = models.CharField( max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH, ) country = CountryField(default=get_default_country) discount_amount = models.DecimalField( max_digits=settings.DEFAULT_MAX_DIGITS, decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0, ) discount = MoneyField(amount_field="discount_amount", currency_field="currency") discount_name = models.CharField(max_length=255, blank=True, null=True) translated_discount_name = models.CharField(max_length=255, blank=True, null=True) voucher_code = models.CharField(max_length=255, blank=True, null=True) gift_cards = models.ManyToManyField(GiftCard, blank=True, related_name="checkouts") redirect_url = models.URLField(blank=True, null=True) tracking_code = models.CharField(max_length=255, blank=True, null=True) language_code = models.CharField(max_length=35, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE) class Meta(ModelWithMetadata.Meta): ordering = ("-last_change", "pk") permissions = ( (CheckoutPermissions.MANAGE_CHECKOUTS.codename, "Manage checkouts"), (CheckoutPermissions.HANDLE_CHECKOUTS.codename, "Handle checkouts"), ) def __iter__(self): return iter(self.lines.all()) def get_customer_email(self) -> Optional[str]: return self.user.email if self.user else self.email def is_shipping_required(self) -> bool: """Return `True` if any of the lines requires shipping.""" return any(line.is_shipping_required() for line in self) def get_total_gift_cards_balance(self) -> Money: """Return the total balance of the gift cards assigned to the checkout.""" balance = self.gift_cards.active( date=date.today()).aggregate( # type: ignore models.Sum( "current_balance_amount"))["current_balance_amount__sum"] if balance is None: return zero_money(currency=self.currency) return Money(balance, self.currency) def get_total_weight(self, lines: Iterable["CheckoutLineInfo"]) -> "Weight": weights = zero_weight() for checkout_line_info in lines: line = checkout_line_info.line weights += line.variant.get_weight() * line.quantity return weights def get_line(self, variant: "ProductVariant") -> Optional["CheckoutLine"]: """Return a line matching the given variant and data if any.""" matching_lines = (line for line in self if line.variant.pk == variant.pk) return next(matching_lines, None) def get_last_active_payment(self) -> Optional["Payment"]: payments = [ payment for payment in self.payments.all() if payment.is_active ] return max(payments, default=None, key=attrgetter("pk")) def set_country(self, country_code: str, commit: bool = False, replace: bool = True): """Set country for checkout.""" if not replace and self.country is not None: return self.country = Country(country_code) if commit: self.save(update_fields=["country"]) def get_country(self): address = self.shipping_address or self.billing_address saved_country = self.country if address is None or not address.country: return saved_country.code country_code = address.country.code if not country_code == saved_country.code: self.set_country(country_code, commit=True) return country_code
class MutatorAttribute(models.Model): mutator = models.ForeignKey('Mutator', models.CASCADE) attribute = models.ForeignKey('TypeAttribute', models.CASCADE) min_modifier = models.DecimalField(max_digits=10, decimal_places=5) max_modifier = models.DecimalField(max_digits=10, decimal_places=5)
class HistoricData(models.Model): """ Historic data model class """ station = models.ForeignKey( Station, verbose_name='stazione', on_delete=models.CASCADE) date = models.DateField('data', auto_now=False, auto_now_add=False) temperature_max = models.DecimalField( 'temperatura massima', max_digits=3, decimal_places=1, blank=True, null=True) temperature_min = models.DecimalField( 'temperatura minima', max_digits=3, decimal_places=1, blank=True, null=True) temperature_mean = models.DecimalField( 'temperatura media', max_digits=3, decimal_places=1, blank=True, null=True) relative_humidity_max = models.DecimalField( 'umidità relativa massima', max_digits=4, decimal_places=1, blank=True, null=True) relative_humidity_min = models.DecimalField( 'umidità relativa minima', max_digits=4, decimal_places=1, blank=True, null=True) relative_humidity_mean = models.DecimalField( 'umidità relativa media', max_digits=4, decimal_places=1, blank=True, null=True) pressure_max = models.DecimalField( 'pressione massima', max_digits=5, decimal_places=1, blank=True, null=True) pressure_min = models.DecimalField( 'pressione minima', max_digits=5, decimal_places=1, blank=True, null=True) pressure_mean = models.DecimalField( 'pressione media', max_digits=5, decimal_places=1, blank=True, null=True) rain = models.DecimalField( 'accumulo precipitazioni', max_digits=8, decimal_places=1, blank=True, null=True) class Meta: verbose_name = 'Dati storici' verbose_name_plural = 'Dati storici' def __str__(self): return '%s - %s' % (self.station, self.date)
class Station(models.Model): # range in seconds for data to be considered live RT_RANGE_SECONDS = 60 * 70 """ Station model """ name = models.CharField('nome', max_length=128) slug = models.SlugField('slug', max_length=128) short_name = models.CharField( 'nome abbreviato', max_length=64, null=True, blank=True) description = RichTextUploadingField('descrizione') climate = RichTextUploadingField('clima', blank=True, null=True) web = models.URLField('sito web', max_length=255, blank=True, null=True) webcam = models.URLField( 'webcam url', max_length=255, blank=True, null=True) image = models.ImageField( upload_to=set_station_image_folder, blank=True, null=True) nation = models.ForeignKey( Nation, verbose_name='nazione', blank=True, null=True, on_delete=models.SET_NULL) region = models.ForeignKey( Region, verbose_name='regione', blank=True, null=True, on_delete=models.SET_NULL) province = models.ForeignKey( Province, verbose_name='provincia', blank=True, null=True, on_delete=models.SET_NULL) address = models.CharField( 'indirizzo', max_length=255, blank=True, null=True) city = models.CharField( 'città/comune', max_length=255, blank=True, null=True) cap = models.CharField('cap', max_length=10, blank=True, null=True) lat = models.CharField('latitudine', max_length=255) lng = models.CharField('longitudine', max_length=255) elevation = models.IntegerField('altitudine') mean_year_rain = models.DecimalField( 'pioggia media annua', max_digits=8, decimal_places=1) station_model = models.CharField('modello stazione', max_length=255) software_model = models.CharField('software', max_length=255) installation_type = models.CharField('tipo intallazione', max_length=255) installation_position = models.CharField('posizionamento', max_length=255) elevation_ground = models.IntegerField('elevazione dal suolo') data_url = models.URLField('url dati', max_length=255) data_format = models.ForeignKey( DataFormat, verbose_name='formato dati', on_delete=models.CASCADE) data_date_format = models.CharField( 'formato data (python)', max_length=128, null=True, blank=True) data_time_format = models.CharField( 'formato ora (python)', max_length=128, null=True, blank=True) forecast_url = models.URLField( 'url sito previsionale', max_length=255, null=True, blank=True) ranking = models.IntegerField('ranking', default=1) active = models.BooleanField('attiva', default=True) objects = StationManager() class Meta: verbose_name = 'stazione' verbose_name_plural = 'stazioni' ordering = ('name', ) def __str__(self): return '%s' % self.name def get_absolute_url(self): return reverse('realtime-station', kwargs={ 'slug': self.slug, }) def now(self): """ Returns the current datetime, for debug and dev purposes """ return timezone.now() # datetime_obj = datetime.datetime(2015, 03, 11, 10, 40, 00) # return timezone.make_aware(datetime_obj, # timezone.get_current_timezone()) def forecast_url_credits(self): if self.forecast_url: return self.forecast_url.replace("forecast.xml", "") return "" def weather_icon(self, encode=False): now = datetime.datetime.now() if now.hour < 6: period = 0 elif now.hour < 12: period = 1 elif now.hour < 18: period = 2 else: period = 3 forecast = StationForecast.objects.filter( station=self.id, date=now.date(), period=period).first() if forecast: icon = '%s%s.png' % (settings.BASE_WEATHER_ICON_URL, forecast.icon) text = forecast.text # @TODO check, probably not needed anymore if encode: return { 'icon': icon.encode('utf-8'), 'text': text.encode('utf-8') } else: return {'icon': icon, 'text': text} else: return None def get_realtime_data(self): """ Last measured data, if inside the Station.RT_RANGE_SECONDS range http://stackoverflow.com/questions/21918802/problems-filtering-django-datetime-field-by-month-and-day """ date = self.now() try: data = Data.objects.filter( station=self.id, datetime__year=date.year, datetime__month=date.month, datetime__day=date.day).order_by('-id').first() time_difference = self.now() - data.datetime if (time_difference.total_seconds() > Station.RT_RANGE_SECONDS): return None return data except: return None def get_day_data(self): """ All data of the current day, @see self.now """ date = self.now() day_data = { 'temperature': [], 'pressure': [], 'relative_humidity': [], 'rain_rate': [], 'rain': [] } data = Data.objects.filter( station=self.id, datetime__year=date.year, datetime__month=date.month, datetime__day=date.day).order_by('id').distinct() for record in data: aux_datetime = timezone.localtime(record.datetime, pytz.timezone( settings.TIME_ZONE)) # noqa datetime_data = { 'datetime_year': aux_datetime.year, 'datetime_month': aux_datetime.month, 'datetime_day': aux_datetime.day, 'datetime_hour': aux_datetime.hour, 'datetime_minute': aux_datetime.minute, 'datetime_second': aux_datetime.second, } temperature_data = datetime_data.copy() temperature_data.update({'value': record.temperature}) day_data['temperature'].append(temperature_data) pressure_data = datetime_data.copy() pressure_data.update({'value': record.pressure}) day_data['pressure'].append(pressure_data) relative_humidity_data = datetime_data.copy() relative_humidity_data.update({'value': record.relative_humidity}) day_data['relative_humidity'].append(relative_humidity_data) rain_rate_data = datetime_data.copy() rain_rate_data.update({'value': record.rain_rate}) day_data['rain_rate'].append(rain_rate_data) rain_data = datetime_data.copy() rain_data.update({'value': record.rain}) day_data['rain'].append(rain_data) return day_data def get_last24_data(self): """ All data of the last 24 hours, @see self.now """ date = self.now() day_data = { 'temperature': [], 'pressure': [], 'relative_humidity': [], 'rain_rate': [], 'rain': [] } date_from = date - datetime.timedelta(days=1) data = Data.objects.filter( station=self.id, datetime__gte=date_from).order_by('id').distinct() for record in data: aux_datetime = timezone.localtime(record.datetime, pytz.timezone( settings.TIME_ZONE)) # noqa datetime_data = { 'datetime_year': aux_datetime.year, 'datetime_month': aux_datetime.month, 'datetime_day': aux_datetime.day, 'datetime_hour': aux_datetime.hour, 'datetime_minute': aux_datetime.minute, 'datetime_second': aux_datetime.second, } temperature_data = datetime_data.copy() temperature_data.update({'value': record.temperature}) day_data['temperature'].append(temperature_data) pressure_data = datetime_data.copy() pressure_data.update({'value': record.pressure}) day_data['pressure'].append(pressure_data) relative_humidity_data = datetime_data.copy() relative_humidity_data.update({'value': record.relative_humidity}) day_data['relative_humidity'].append(relative_humidity_data) rain_rate_data = datetime_data.copy() rain_rate_data.update({'value': record.rain_rate}) day_data['rain_rate'].append(rain_rate_data) rain_data = datetime_data.copy() rain_data.update({'value': record.rain}) day_data['rain'].append(rain_data) return day_data def get_historic_data(self, from_date, to_date): historic_data = [] data = HistoricData.objects.filter( station=self.id, date__gte=from_date, date__lte=to_date).order_by('date').distinct() for record in data: historic_data.append({ 'date_obj': record.date, 'date': record.date.strftime('%Y-%m-%d'), 'temperature_mean': record.temperature_mean, 'temperature_max': record.temperature_max, 'temperature_min': record.temperature_min, 'pressure_mean': record.pressure_mean, 'pressure_max': record.pressure_max, 'pressure_min': record.pressure_min, 'relative_humidity_mean': record.relative_humidity_mean, 'relative_humidity_max': record.relative_humidity_max, 'relative_humidity_min': record.relative_humidity_min, 'rain': record.rain }) return historic_data def get_data_first_date(self): data = HistoricData.objects.filter( station=self.id).order_by('date').distinct()[0] return data.date
class Migration(migrations.Migration): initial = True dependencies = [ ('cashdesk', '0001_initial'), ('nomenclature', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Delivery', fields=[ ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='Номер')), ('order_date', models.DateField(default=django.utils.timezone.now, verbose_name='Дата на заявка')), ('status', models.CharField(choices=[('ORDERED', 'ПОРЪЧАНO'), ('DELIVERED', 'ДОСТАВЕНО'), ('CANCELED', 'ОТКАЗАНО')], default='ORDERED', max_length=80, verbose_name='Статус')), ('delivery_date', models.DateField(blank=True, null=True, verbose_name='Дата на доставка')), ('invoice_no', models.CharField(blank=True, max_length=400, null=True, verbose_name='Номер на фактура')), ('firm_invoice_no', models.CharField(blank=True, max_length=400, null=True, verbose_name='Факт. На фирма:')), ('paid', models.CharField(choices=[('НЕ', 'НЕ'), ('ДА', 'ДА')], default='НЕ', max_length=80, verbose_name='Платено')), ('notes', models.TextField(blank=True, max_length=2000, null=True, verbose_name='Забележка')), ('last_update_date', models.DateTimeField(blank=True, null=True, verbose_name='Дата на опресняване')), ('cashdesk_fk', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='cashdesk.Cashdesk', verbose_name='Дата на плащане')), ('club_fk', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nomenclature.Club', verbose_name='Клуб')), ('supplier_fk', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nomenclature.Supplier', verbose_name='Доставчик')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='Служител')), ], options={ 'managed': True, 'verbose_name': 'Доставка', 'verbose_name_plural': 'Доставки', 'db_table': 'delivery', }, ), migrations.CreateModel( name='DeliveryDetail', fields=[ ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='Номер')), ('cnt', models.DecimalField(decimal_places=3, max_digits=8, verbose_name='Количество')), ('price', models.DecimalField(decimal_places=2, max_digits=8, verbose_name='Единична цена')), ], options={ 'managed': True, 'verbose_name': 'Доставка описание', 'verbose_name_plural': 'Доставки описание', 'db_table': 'delivery_detail', }, ), migrations.CreateModel( name='ArticleDelivery', fields=[ ], options={ 'verbose_name': 'Артикул доставки', 'verbose_name_plural': 'Артикули доставки', 'proxy': True, }, bases=('nomenclature.article',), ), migrations.AddField( model_name='deliverydetail', name='article_fk', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='delivery.ArticleDelivery', verbose_name='Артикул'), ), migrations.AddField( model_name='deliverydetail', name='delivery_fk', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='delivery.Delivery', verbose_name='Доставка N'), ), ]
class Data(models.Model): """ Realtime data model class """ station = models.ForeignKey( Station, verbose_name='stazione', on_delete=models.CASCADE) datetime = models.DateTimeField( 'data e ora', auto_now=False, auto_now_add=False) temperature = models.DecimalField( 'temperatura', max_digits=3, decimal_places=1, blank=True, null=True) temperature_max = models.DecimalField( 'temperatura massima', max_digits=3, decimal_places=1, blank=True, null=True) temperature_max_time = models.TimeField( 'ora temperatura massima', blank=True, null=True) temperature_min = models.DecimalField( 'temperatura minima', max_digits=3, decimal_places=1, blank=True, null=True) temperature_min_time = models.TimeField( 'ora temperatura minima', blank=True, null=True) relative_humidity = models.DecimalField( 'umidità relativa', max_digits=4, decimal_places=1, blank=True, null=True) relative_humidity_max = models.DecimalField( 'umidità relativa massima', max_digits=4, decimal_places=1, blank=True, null=True) relative_humidity_max_time = models.TimeField( 'ora umidità relativa massima', blank=True, null=True) relative_humidity_min = models.DecimalField( 'umidità relativa minima', max_digits=4, decimal_places=1, blank=True, null=True) relative_humidity_min_time = models.TimeField( 'ora umidità relativa minima', blank=True, null=True) dewpoint = models.DecimalField( 'dewpoint', max_digits=3, decimal_places=1, blank=True, null=True) dewpoint_max = models.DecimalField( 'dewpoint massima', max_digits=3, decimal_places=1, blank=True, null=True) dewpoint_max_time = models.TimeField( 'ora dewpoint massima', blank=True, null=True) dewpoint_min = models.DecimalField( 'dewpoint minima', max_digits=3, decimal_places=1, blank=True, null=True) dewpoint_min_time = models.TimeField( 'ora dewpoint minima', blank=True, null=True) pressure = models.DecimalField( 'pressione', max_digits=5, decimal_places=1, blank=True, null=True) pressure_max = models.DecimalField( 'pressione massima', max_digits=5, decimal_places=1, blank=True, null=True) pressure_max_time = models.TimeField( 'ora pressione massima', blank=True, null=True) pressure_min = models.DecimalField( 'pressione minima', max_digits=5, decimal_places=1, blank=True, null=True) pressure_min_time = models.TimeField( 'ora pressione minima', blank=True, null=True) wind_strength = models.DecimalField( 'vento', max_digits=4, decimal_places=1, blank=True, null=True) wind_dir = models.CharField( 'direzione vento', max_length=10, blank=True, null=True) wind_strength_max = models.DecimalField( 'vento massimo', max_digits=4, decimal_places=1, blank=True, null=True) wind_dir_max = models.CharField( 'direzione vento massimo', max_length=10, blank=True, null=True) wind_max_time = models.TimeField( 'ora vento massimo', blank=True, null=True) rain = models.DecimalField( 'accumulo precipitazioni', max_digits=8, decimal_places=1, blank=True, null=True) rain_rate = models.DecimalField( 'rateo precipitazioni', max_digits=8, decimal_places=1, blank=True, null=True) rain_rate_max = models.DecimalField( 'rateo massimo precipitazioni', max_digits=8, decimal_places=1, blank=True, null=True) rain_rate_max_time = models.TimeField( 'ora rateo massimo precipitazioni', blank=True, null=True) rain_month = models.DecimalField( 'accumulo mensile precipitazioni', max_digits=8, decimal_places=1, blank=True, null=True) rain_year = models.DecimalField( 'accumulo annuale precipitazioni', max_digits=8, decimal_places=1, blank=True, null=True) class Meta: verbose_name = 'Dati realtime' verbose_name_plural = 'Dati realtime' def __str__(self): return '%s - %s' % (self.station.name, str(self.datetime) if self.datetime else '') @property def wind_dir_text(self): if self.wind_dir: try: return wind_dir_text_base(self.wind_dir) except: pass return '' @property def wind_dir_max_text(self): if self.wind_dir_max: try: return wind_dir_text_base(self.wind_dir_max) except: pass return ''
class OrderItem(models.Model): item_type = models.IntegerField(u"Type d'item", choices = ORDERITEM_TYPES, default = 0) username = models.CharField(u"Commandé par", max_length = 100) username_recept = models.CharField(u"Réceptionné par", max_length = 100, null = True, blank = True) product_id = models.IntegerField(u'ID produit', blank = True, null = True) name = models.CharField(u'Désignation', max_length = 500) provider = models.CharField(u'Fournisseur', max_length = 100, blank = True, null = True) origin = models.CharField(u"Fournisseur d'origine", max_length = 100, blank = True, null = True) packaging = models.CharField(u'Conditionnement', max_length = 100, blank = True, null = True) reference = models.CharField(u'Référence', max_length = 100, blank = True, null = True) offer_nb = models.CharField(u'N° Offre', max_length = 100, blank = True, null = True) category = models.CharField(u'Type', max_length = 100, blank = True, null = True) sub_category = models.CharField(u'Sous-type', max_length = 100, blank = True, null = True) nomenclature = models.CharField(u'Nomenclature', max_length = 100, blank = True, null = True) price = models.DecimalField(u'Montant', max_digits = 12, decimal_places = 2) cost_type = models.IntegerField(u'Type de coût', choices = COST_TYPE_CHOICES) quantity = models.IntegerField(u'Quantité', default = 1) delivered = models.IntegerField(u'Quantité à livrer', default = 0) is_confidential = models.BooleanField(u"Confidentielle?", default = False) class Meta: db_table = 'order_item' verbose_name = "Item de commande" verbose_name_plural = "Items de commande" ordering = ('id',) def get_order(self): return self.order_set.get() def get_history(self): return self.history_set.get() def get_fullname(self): users = User.objects.filter(username = self.username) if users.count() > 0 and users[0].get_full_name(): return u"%s" % users[0].get_full_name() else: return u"%s" % self.username def get_fullname_recept(self): users = User.objects.filter(username = self.username_recept) if users.count() > 0 and users[0].get_full_name(): return u"%s" % users[0].get_full_name() elif self.username_recept: return u"%s" % self.username_recept else: return None def total_price(self): if self.cost_type == DEBIT: return self.price * self.quantity if self.cost_type == CREDIT: return self.price * self.quantity * -1 def create_budget_line(self): try: order = self.order_set.get() except Order.DoesNotExist: return if not order.budget: return bl = BudgetLine.objects.create( team = order.budget.team.name, order_id = order.id, orderitem_id = self.id, budget_id = order.budget.id, budget = order.budget.name, number = order.number, nature = order.budget.default_nature, budget_type = order.budget.budget_type, origin = order.budget.default_origin, provider = order.provider.name, offer = self.offer_nb, product = self.name, product_price = self.total_price(), reference = self.reference, quantity = self.quantity ) if self.cost_type == DEBIT: bl.credit = 0 bl.debit = self.price elif self.cost_type == CREDIT: bl.credit = self.price bl.debit = 0 bl.save() def update_budget_line(self): try: bl = BudgetLine.objects.get(orderitem_id = self.id) except: return if self.cost_type == DEBIT: bl.credit = 0 bl.debit = self.price elif self.cost_type == CREDIT: bl.credit = self.price bl.debit = 0 else: raise Exception("COST TYPE SHOULD NOT BE NULL") bl.provider = bl.provider and bl.provider or self.provider bl.offer = self.offer_nb bl.product = self.name bl.product_price = self.total_price() bl.reference = self.reference bl.quantity = self.quantity bl.save() def update_product(self): if self.product_id: product = Product.objects.get(id = self.product_id) orig_price = product.price if orig_price != self.price and product.has_expired(): product.expiry = datetime(timezone.now().year, 12, 31) product.name = self.name product.packaging = self.packaging product.reference = self.reference product.offer_nb = self.offer_nb product.nomenclature = self.nomenclature product.price = self.price product.save()
class ProductInOrder(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, blank=True, null=True, default=None) product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, default=None) number = models.IntegerField(default=1) price_per_item = models.DecimalField(max_digits=10, decimal_places=1, default=0) total_price = models.DecimalField(max_digits=10, decimal_places=1, default=0) #price*number is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return " %s" % self.order class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары в заказе' def save(self, *args, **kwargs): price_per_item = self.product.price self.price_per_item = price_per_item self.total_price = self.number * self.price_per_item order = self.order all_products_in_order = ProductInOrder.objects.filter(order=order, is_active=True) order_total_price = 0 for item in all_products_in_order: item.total_price += item.total_price order_total_price = self.total_price self.order.total_price = order_total_price self.order.save(force_update=True) super(ProductInOrder, self).save(*args, **kwargs) def product_in_order_post_save(sender, instance, created, **kwargs): order = instance.order all_products_in_order = ProductInOrder.objects.filter(order=order, is_active=True) order_total_price = 0 for item in all_products_in_order: order_total_price += item.total_price instance.order.total_price = order_total_price instance.order.save(force_update=True) post_save.connect(product_in_order_post_save, sender=Product)
class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='City', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='', max_length=50)), ('slug', models.SlugField()), ], options={ 'verbose_name': 'city', 'verbose_name_plural': 'cities', 'ordering': ('name',), }, ), migrations.CreateModel( name='FoodType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='', max_length=100)), ('slug', models.SlugField()), ], options={ 'verbose_name': 'food_type', 'verbose_name_plural': 'food_types', 'ordering': ('name',), }, ), migrations.CreateModel( name='RestaurantType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='', max_length=100)), ('slug', models.SlugField()), ], options={ 'verbose_name': 'rest_type', 'verbose_name_plural': 'rest_types', 'ordering': ('name',), }, ), migrations.CreateModel( name='Restaurant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='', max_length=255)), ('slug', models.SlugField()), ('image', models.ImageField(blank=True, upload_to='')), ('mini_description', models.CharField(default='', max_length=255)), ('address', models.CharField(default='', max_length=255)), ('open', models.BooleanField(default=True)), ('open_time', models.TimeField()), ('close_time', models.TimeField()), ('rest_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='main.RestaurantType')), ], options={ 'verbose_name': 'restaurant', 'verbose_name_plural': 'restaurants', 'ordering': ('name',), }, ), migrations.CreateModel( name='Ingredient', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='', max_length=100)), ('slug', models.SlugField()), ('restaurant', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='main.Restaurant')), ], options={ 'verbose_name': 'ingredient', 'verbose_name_plural': 'ingredients', 'ordering': ('name',), }, ), migrations.CreateModel( name='Food', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='', max_length=255)), ('slug', models.SlugField()), ('price', models.DecimalField(decimal_places=2, max_digits=10)), ('food_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='foods', to='main.FoodType')), ('ingredients', models.ManyToManyField(to='main.Ingredient')), ('restaurant', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='foods', to='main.Restaurant')), ], options={ 'verbose_name': 'food', 'verbose_name_plural': 'foods', 'ordering': ('name',), }, ), ]
class Migration(migrations.Migration): initial = True dependencies = [ ('Braumat', '0001_initial'), ('BPCS', '0001_initial'), ('RecipeManager', '0001_initial'), ] operations = [ migrations.CreateModel( name='Batch', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('year', models.PositiveSmallIntegerField()), ('order', models.PositiveSmallIntegerField()), ('batch', models.PositiveSmallIntegerField()), ('date', models.DateField(blank=True, null=True)), ('locked', models.BooleanField(default=False)), ('analyzed', models.BooleanField(default=False)), ('ph', models.DecimalField(blank=True, decimal_places=2, default=None, max_digits=3, null=True, verbose_name='Mash pH')), ('first_wort', models.DecimalField(blank=True, decimal_places=2, default=None, max_digits=4, null=True, verbose_name='First Wort')), ('last_wort', models.DecimalField(blank=True, decimal_places=2, default=None, max_digits=4, null=True, verbose_name='Last Wort')), ('sob', models.DecimalField(blank=True, decimal_places=2, default=None, max_digits=4, null=True, verbose_name='Start of Boil')), ('ko', models.DecimalField(blank=True, decimal_places=2, default=None, max_digits=4, null=True, verbose_name='Kettle Out')), ('mf_vol', models.DecimalField(blank=True, decimal_places=1, default=None, max_digits=4, null=True, verbose_name='Mash Filter Volume')), ('balling', models.DecimalField(blank=True, decimal_places=2, default=None, max_digits=4, null=True, verbose_name='Metered Balling')), ('bbls', models.DecimalField(blank=True, decimal_places=1, default=None, max_digits=5, null=True, verbose_name='Metered Barrels')), ('master_recipe', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='hotblock_batch_set', related_query_name='hotblock_batch', to='Braumat.MasterRecipe')), ('recipe', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='RecipeManager.Recipe')), ], options={ 'verbose_name': 'Hot block batch', 'verbose_name_plural': 'Hot block batches', 'ordering': ('-year', '-order', 'batch'), 'abstract': False, }, ), migrations.CreateModel( name='BatchMaterial', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('amount', models.FloatField()), ('extract_potential', models.DecimalField(blank=True, decimal_places=4, max_digits=5, null=True)), ('lot_number', models.CharField(blank=True, max_length=255, null=True)), ('batch', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='batchmaterial_set', related_query_name='batchmaterial', to='HotBlock.Batch')), ('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='hotblock_batchmaterial_set', related_query_name='hotblock_batchmaterial', to='BPCS.BPCSItem')), ('unit', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='hotblock_batchmaterial_set', related_query_name='hotblock_batchmaterial', to='BPCS.Unit')), ], options={ 'verbose_name': 'Hot batch material', 'ordering': ('-extract_potential', '-amount'), 'abstract': False, }, ), migrations.CreateModel( name='StepRecord', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('start_time', models.DateTimeField()), ('end_time', models.DateTimeField()), ('name_01', models.CharField(blank=True, max_length=125, null=True)), ('dimension_01', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_01', models.CharField(blank=True, max_length=50, null=True)), ('process_value_01', models.CharField(blank=True, max_length=50, null=True)), ('name_02', models.CharField(blank=True, max_length=125, null=True)), ('dimension_02', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_02', models.CharField(blank=True, max_length=50, null=True)), ('process_value_02', models.CharField(blank=True, max_length=50, null=True)), ('name_03', models.CharField(blank=True, max_length=125, null=True)), ('dimension_03', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_03', models.CharField(blank=True, max_length=50, null=True)), ('process_value_03', models.CharField(blank=True, max_length=50, null=True)), ('name_04', models.CharField(blank=True, max_length=125, null=True)), ('dimension_04', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_04', models.CharField(blank=True, max_length=50, null=True)), ('process_value_04', models.CharField(blank=True, max_length=50, null=True)), ('name_05', models.CharField(blank=True, max_length=125, null=True)), ('dimension_05', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_05', models.CharField(blank=True, max_length=50, null=True)), ('process_value_05', models.CharField(blank=True, max_length=50, null=True)), ('name_06', models.CharField(blank=True, max_length=125, null=True)), ('dimension_06', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_06', models.CharField(blank=True, max_length=50, null=True)), ('process_value_06', models.CharField(blank=True, max_length=50, null=True)), ('name_07', models.CharField(blank=True, max_length=125, null=True)), ('dimension_07', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_07', models.CharField(blank=True, max_length=50, null=True)), ('process_value_07', models.CharField(blank=True, max_length=50, null=True)), ('name_08', models.CharField(blank=True, max_length=125, null=True)), ('dimension_08', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_08', models.CharField(blank=True, max_length=50, null=True)), ('process_value_08', models.CharField(blank=True, max_length=50, null=True)), ('name_09', models.CharField(blank=True, max_length=125, null=True)), ('dimension_09', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_09', models.CharField(blank=True, max_length=50, null=True)), ('process_value_09', models.CharField(blank=True, max_length=50, null=True)), ('name_10', models.CharField(blank=True, max_length=125, null=True)), ('dimension_10', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_10', models.CharField(blank=True, max_length=50, null=True)), ('process_value_10', models.CharField(blank=True, max_length=50, null=True)), ('name_11', models.CharField(blank=True, max_length=125, null=True)), ('dimension_11', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_11', models.CharField(blank=True, max_length=50, null=True)), ('process_value_11', models.CharField(blank=True, max_length=50, null=True)), ('name_12', models.CharField(blank=True, max_length=125, null=True)), ('dimension_12', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_12', models.CharField(blank=True, max_length=50, null=True)), ('process_value_12', models.CharField(blank=True, max_length=50, null=True)), ('name_13', models.CharField(blank=True, max_length=125, null=True)), ('dimension_13', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_13', models.CharField(blank=True, max_length=50, null=True)), ('process_value_13', models.CharField(blank=True, max_length=50, null=True)), ('name_14', models.CharField(blank=True, max_length=125, null=True)), ('dimension_14', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_14', models.CharField(blank=True, max_length=50, null=True)), ('process_value_14', models.CharField(blank=True, max_length=50, null=True)), ('name_15', models.CharField(blank=True, max_length=125, null=True)), ('dimension_15', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_15', models.CharField(blank=True, max_length=50, null=True)), ('process_value_15', models.CharField(blank=True, max_length=50, null=True)), ('name_16', models.CharField(blank=True, max_length=125, null=True)), ('dimension_16', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_16', models.CharField(blank=True, max_length=50, null=True)), ('process_value_16', models.CharField(blank=True, max_length=50, null=True)), ('name_17', models.CharField(blank=True, max_length=125, null=True)), ('dimension_17', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_17', models.CharField(blank=True, max_length=50, null=True)), ('process_value_17', models.CharField(blank=True, max_length=50, null=True)), ('name_18', models.CharField(blank=True, max_length=125, null=True)), ('dimension_18', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_18', models.CharField(blank=True, max_length=50, null=True)), ('process_value_18', models.CharField(blank=True, max_length=50, null=True)), ('name_19', models.CharField(blank=True, max_length=125, null=True)), ('dimension_19', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_19', models.CharField(blank=True, max_length=50, null=True)), ('process_value_19', models.CharField(blank=True, max_length=50, null=True)), ('name_20', models.CharField(blank=True, max_length=125, null=True)), ('dimension_20', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_20', models.CharField(blank=True, max_length=50, null=True)), ('process_value_20', models.CharField(blank=True, max_length=50, null=True)), ('name_21', models.CharField(blank=True, max_length=125, null=True)), ('dimension_21', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_21', models.CharField(blank=True, max_length=50, null=True)), ('process_value_21', models.CharField(blank=True, max_length=50, null=True)), ('name_22', models.CharField(blank=True, max_length=125, null=True)), ('dimension_22', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_22', models.CharField(blank=True, max_length=50, null=True)), ('process_value_22', models.CharField(blank=True, max_length=50, null=True)), ('name_23', models.CharField(blank=True, max_length=125, null=True)), ('dimension_23', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_23', models.CharField(blank=True, max_length=50, null=True)), ('process_value_23', models.CharField(blank=True, max_length=50, null=True)), ('name_24', models.CharField(blank=True, max_length=125, null=True)), ('dimension_24', models.CharField(blank=True, max_length=50, null=True)), ('setpoint_24', models.CharField(blank=True, max_length=50, null=True)), ('process_value_24', models.CharField(blank=True, max_length=50, null=True)), ('batch', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='steprecord_set', related_query_name='steprecord', to='HotBlock.Batch')), ('step', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='hotblock_steprecord_set', related_query_name='hotblock_steprecord', to='Braumat.SequenceStep')), ], options={ 'verbose_name': 'Hot step record', 'ordering': ('-batch', '-start_time'), 'abstract': False, }, ), migrations.AlterUniqueTogether( name='steprecord', unique_together={('batch', 'step', 'start_time')}, ), migrations.AlterUniqueTogether( name='batchmaterial', unique_together={('batch', 'item')}, ), migrations.AlterUniqueTogether( name='batch', unique_together={('year', 'order', 'batch', 'master_recipe')}, ), ]
class HistoricAirQualityData(models.Model): station = models.ForeignKey(AirQualityStation, verbose_name='stazione', on_delete=models.CASCADE, related_name='historic_data', ) date = models.DateField('data', auto_now=False, auto_now_add=False) air_quality_index_max = models.DecimalField( 'indice qualità dell\'aria massimo', max_digits=4, decimal_places=1) air_quality_index_min = models.DecimalField( 'indice qualità dell\'aria minimo', max_digits=4, decimal_places=1) air_quality_index_mean = models.DecimalField( 'indice qualità dell\'aria medio', max_digits=4, decimal_places=1) pm1_max = models.DecimalField('pm 1 massimo', max_digits=8, decimal_places=1) pm1_min = models.DecimalField('pm 1 minimo', max_digits=8, decimal_places=1) pm1_mean = models.DecimalField('pm 1 minimo', max_digits=8, decimal_places=1) pm25_max = models.DecimalField('pm 2.5 massimo', max_digits=8, decimal_places=1) pm25_min = models.DecimalField('pm 2.5 minimo', max_digits=8, decimal_places=1) pm25_mean = models.DecimalField('pm 2.5 minimo', max_digits=8, decimal_places=1) pm10_max = models.DecimalField('pm 10 massimo', max_digits=8, decimal_places=1) pm10_min = models.DecimalField('pm 10 minimo', max_digits=8, decimal_places=1) pm10_mean = models.DecimalField('pm 10 minimo', max_digits=8, decimal_places=1) class Meta: verbose_name = 'Dati storici qualità dell\'aria' verbose_name_plural = 'Dati storici qualità dell\'aria' def __str__(self): return '%s - %s' % (self.station, self.date)
class Migration(migrations.Migration): replaces = [('service', '0001_initial'), ('service', '0002_auto_20180727_1446'), ('service', '0003_timeframe_minutes')] initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Market', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=30)), ], ), migrations.CreateModel( name='Pair', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=80)), ('market', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='service.Market')), ], ), migrations.CreateModel( name='PairData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('high_price', models.DecimalField(decimal_places=5, max_digits=10)), ('low_price', models.DecimalField(decimal_places=5, max_digits=10)), ('open_price', models.DecimalField(decimal_places=5, max_digits=10)), ('close_price', models.DecimalField(decimal_places=5, max_digits=10)), ('volume', models.DecimalField(decimal_places=5, max_digits=10)), ('open_time', models.DateTimeField(default=django.utils.timezone.now)), ('close_time', models.DateTimeField(default=django.utils.timezone.now)), ], ), migrations.CreateModel( name='PairIndex', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pair', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='service.Pair')), ], ), migrations.CreateModel( name='Timeframe', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=16)), ('minutes', models.IntegerField(default=1)), ], ), migrations.AddField( model_name='pairindex', name='timeframe', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='service.Timeframe'), ), migrations.AddField( model_name='pairdata', name='pair_index', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='service.PairIndex'), ), ]
class TimeSeries(models.Model): forecast = models.ForeignKey(Forecast, on_delete=models.CASCADE) feelsLikeTemperature = models.DecimalField('feels like', max_digits=4, decimal_places=2, blank=True, null=True) max10mWindGust = models.DecimalField('max. 10m wind gust', max_digits=10, decimal_places=6, blank=True, null=True) maxScreenAirTemp = models.DecimalField('maximum temperature', max_digits=9, decimal_places=6, blank=True, null=True) minScreenAirTemp = models.DecimalField('minimum temperature', max_digits=9, decimal_places=6, blank=True, null=True) mslp = models.DecimalField('pressure', max_digits=7, decimal_places=2, blank=True, null=True) precipitationRate = models.DecimalField('Rainfall rate', max_digits=5, decimal_places=2, blank=True, null=True) probOfPrecipitation = models.IntegerField('Chance of rain', blank=True, null=True) screenDewPointTemperature = models.DecimalField('dew point', max_digits=5, decimal_places=2, blank=True, null=True) screenRelativeHumidity = models.DecimalField('Humidity', max_digits=5, decimal_places=2, blank=True, null=True) screenTemperature = models.DecimalField('temperature', max_digits=5, decimal_places=2, blank=True, null=True) significantWeatherCode = models.IntegerField('weather code', blank=True, null=True) def get_symbol(self): with connection.cursor() as cursor: cursor.execute( "SELECT symbol_image from forecast_symbol where weather_code = %s", [self.significantWeatherCode]) row = cursor.fetchone() #breakpoint() return row[0] series_time = models.DateTimeField('time') totalPrecipAmount = models.DecimalField('total precipitation', max_digits=5, decimal_places=2, blank=True, null=True) totalSnowAmount = models.DecimalField('snow amount', max_digits=5, decimal_places=2, blank=True, null=True) uvIndex = models.IntegerField('UV', blank=True, null=True) visibility = models.IntegerField('visibility', blank=True, null=True) windDirectionFrom10m = models.IntegerField('wind direction', blank=True, null=True) def get_arrow(self): def get_rose(degrees): #Utility to convert degrees to a human direction # At the moment I only have a limited arrow set sectors = [ "N", #"NNE", "NE", #"ENE", "E", #"ESE", "SE", #"SSE", "S", #"SSW", "SW", #"WSW", "W", #"WNW", "NW", #"NNW", "N" ] big_degrees = (360 + 22.5) + degrees sector = int(big_degrees / 45) #force into range 0-7, with 0 = N if sector >= 8: sector -= 8 return sectors[sector] # end of get_rose rose = get_rose(self.windDirectionFrom10m) # produces 'NW', 'SE' etc with connection.cursor() as cursor: cursor.execute( "SELECT arrow_image from forecast_arrow where direction_from = %s", [rose]) row = cursor.fetchone() #breakpoint() return row[0] windGustSpeed10m = models.DecimalField('wind gust', max_digits=5, decimal_places=2, blank=True, null=True) windSpeed10m = models.DecimalField('wind speed', max_digits=5, decimal_places=2, blank=True, null=True) probOfSnow = models.IntegerField('chance of snow', blank=True, null=True) probOfHeavySnow = models.IntegerField('chance of heavy snow', blank=True, null=True) probOfRain = models.IntegerField('chance of rain', blank=True, null=True) probOfHeavyRain = models.IntegerField('chance of heavy rain', blank=True, null=True) probOfHail = models.IntegerField('chance of hail', blank=True, null=True) probOfSferics = models.IntegerField('chance of lightning (sferics)', blank=True, null=True) class Meta: ordering = ['series_time']
class Migration(migrations.Migration): dependencies = [ ('contents', '0004_shopnews'), ] operations = [ migrations.CreateModel( name='FoodType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('typeid', models.IntegerField(verbose_name='商品分类id')), ('typename', models.CharField(max_length=100, verbose_name='商品分类名称')), ('childtypename', models.CharField(max_length=500, verbose_name='子分类的名称')), ('childtypeid', models.IntegerField(verbose_name='子分类的id')), ('brand', models.CharField(max_length=500, verbose_name='推荐品牌')), ('activityid', models.IntegerField(verbose_name='热门活动id')), ], options={ 'db_table': 'myshop_goodstype', }, ), migrations.CreateModel( name='Goods', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('goodsid', models.IntegerField(verbose_name='商品id')), ('img', models.CharField(max_length=100, verbose_name='商品图片')), ('name', models.CharField(max_length=200, verbose_name='商品短名称')), ('specifics', models.CharField(max_length=100, verbose_name='商品规格')), ('price', models.DecimalField(decimal_places=2, max_digits=6, verbose_name='售价')), ('marketprice', models.DecimalField(decimal_places=2, max_digits=6, verbose_name='市场价')), ('categoryid', models.IntegerField(verbose_name='所属分类id')), ('childcid', models.IntegerField(verbose_name='所属子分类id')), ('childcidname', models.CharField(max_length=100, verbose_name='自分类名称')), ('inventory', models.IntegerField(verbose_name='库存')), ('sales', models.IntegerField(verbose_name='销量')), ], options={ 'db_table': 'myshop_goods', }, ), migrations.CreateModel( name='HotActivitys', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('activityid', models.IntegerField(verbose_name='热门活动id')), ('img', models.CharField(max_length=150, verbose_name='活动图片信息')), ('links', models.CharField(max_length=150, verbose_name='活动路径')), ], options={ 'db_table': 'myshop_activities', }, ), ]
class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Node', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=30)), ('email', models.EmailField(default=None, max_length=254, null=True)), ('address', models.CharField(max_length=255)), ('code', models.IntegerField()), ('oauth', django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True)), ('active', models.BooleanField(default=True)), ('co_owners', models.ManyToManyField(related_name='owners', to=settings.AUTH_USER_MODEL)), ('managers', models.ManyToManyField(limit_choices_to={'is_manager': True}, related_name='managers', to=settings.AUTH_USER_MODEL)), ('owner', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='owner', to=settings.AUTH_USER_MODEL)), ('workers', models.ManyToManyField(related_name='workers', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Partner', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('street_address', models.CharField(max_length=255)), ('email', models.EmailField(blank=True, max_length=254)), ('active', models.BooleanField(default=True)), ('other_names', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=50), blank=True, null=True, size=None)), ('of_node', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='business_logic.Node')), ], ), migrations.CreateModel( name='Order', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('html', models.TextField(blank=True)), ('result', models.CharField(blank=True, max_length=20)), ('source', models.CharField(blank=True, max_length=30)), ('customer_phone', models.CharField(max_length=30)), ('order_number', models.CharField(max_length=200, unique=True)), ('name', models.CharField(max_length=200)), ('address', models.CharField(max_length=300)), ('deliver_by', models.CharField(max_length=200)), ('entry_date', models.DateTimeField(auto_now_add=True)), ('total_price', models.DecimalField(decimal_places=2, max_digits=6)), ('tip', models.DecimalField(decimal_places=2, max_digits=6)), ('delivery_fee', models.DecimalField(decimal_places=2, max_digits=6)), ('note', models.CharField(blank=True, max_length=300)), ('in_progress', models.BooleanField(default=False)), ('complete', models.BooleanField(default=False)), ('completed_time', models.DateTimeField(blank=True, null=True)), ('assigned_to', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='assigned_user', to=settings.AUTH_USER_MODEL)), ('store', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='store', to='business_logic.Partner')), ], ), ]
class RegisteredTransactions(BaseModel): sender = models.ForeignKey(get_user_model(), on_delete=models.DO_NOTHING) reciever = models.EmailField() type = models.CharField(max_length=200) amount = models.DecimalField(max_digits=18, decimal_places=8) is_successful = models.BooleanField(default=False)
class Migration(migrations.Migration): dependencies = [ ('holidays', '0050_auto_20210416_1645'), ] operations = [ migrations.AddField( model_name='orderforpackage', name='discount', field=models.DecimalField(blank=True, decimal_places=2, default=0.0, max_digits=5), ), migrations.AlterField( model_name='affialiate_click', name='date_logged_in', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 115358, tzinfo=utc)), ), migrations.AlterField( model_name='affiliate_info_user', name='updated_on', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 115358, tzinfo=utc)), ), migrations.AlterField( model_name='affiliate_success', name='date_affiliate_successfull', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 115358, tzinfo=utc)), ), migrations.AlterField( model_name='affiliate_transaction', name='date_of_transaction', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 115358, tzinfo=utc)), ), migrations.AlterField( model_name='affiliateaccounts', name='date_joined', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 99666, tzinfo=utc)), ), migrations.AlterField( model_name='affiliateinfo', name='date_edited', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 99666, tzinfo=utc)), ), migrations.AlterField( model_name='banner', name='datecreated', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 115358, tzinfo=utc)), ), migrations.AlterField( model_name='blogs', name='createdat', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 99666, tzinfo=utc)), ), migrations.AlterField( model_name='comments', name='commented_on', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 99666, tzinfo=utc)), ), migrations.AlterField( model_name='destinations', name='timecreated', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 115358, tzinfo=utc)), ), migrations.AlterField( model_name='hotels', name='datetime', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 23, 11, 2, 99666)), ), migrations.AlterField( model_name='hotels', name='hotel_updatedon', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 99666, tzinfo=utc)), ), migrations.AlterField( model_name='offers', name='created_at', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 99666, tzinfo=utc)), ), migrations.AlterField( model_name='offers', name='valid_to', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 99666, tzinfo=utc)), ), migrations.AlterField( model_name='order', name='date_ordered', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 99666, tzinfo=utc)), ), migrations.AlterField( model_name='orderforpackage', name='date_ordered', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 99666, tzinfo=utc)), ), migrations.AlterField( model_name='packages', name='package_created', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 99666, tzinfo=utc)), ), migrations.AlterField( model_name='promo_used', name='used_at', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 115358, tzinfo=utc)), ), migrations.AlterField( model_name='promocode', name='time_created', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 115358, tzinfo=utc)), ), migrations.AlterField( model_name='reviews', name='datecreated', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 115358, tzinfo=utc)), ), migrations.AlterField( model_name='services', name='time_created', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 115358, tzinfo=utc)), ), migrations.AlterField( model_name='transport', name='datetime', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 99666, tzinfo=utc)), ), migrations.AlterField( model_name='userinfo', name='datetime', field=models.DateTimeField(default=datetime.datetime(2021, 4, 20, 17, 41, 2, 99666, tzinfo=utc)), ), ]
class Migration(migrations.Migration): dependencies = [ ('foodcartapp', '0047_auto_20200727_1217'), ] operations = [ migrations.CreateModel( name='Basket', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('quantity', models.PositiveSmallIntegerField(verbose_name='Количество')), ('price', models.DecimalField(decimal_places=2, max_digits=8, verbose_name='цена')), ], options={ 'verbose_name': 'элемент заказа', 'verbose_name_plural': 'элементы заказа', }, ), migrations.AlterField( model_name='order', name='called_at', field=models.DateTimeField(blank=True, db_index=True, null=True, verbose_name='Дата звонка'), ), migrations.AlterField( model_name='order', name='comment', field=models.TextField(blank=True, verbose_name='Комментарий'), ), migrations.AlterField( model_name='order', name='delivered_at', field=models.DateTimeField(blank=True, db_index=True, null=True, verbose_name='Дата доставки заказа'), ), migrations.AlterField( model_name='order', name='payment_type', field=models.CharField(choices=[('online', 'Электронно'), ('cash', 'Наличностью')], db_index=True, default='cash', max_length=20, verbose_name='Способ оплаты'), ), migrations.AlterField( model_name='order', name='registered_at', field=models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Дата создания заказа'), ), migrations.AlterField( model_name='order', name='status', field=models.CharField(choices=[('unprocessed', 'Необработанный'), ('processed', 'Обработанный')], db_index=True, default='unprocessed', max_length=20, verbose_name='Статус заказа'), ), migrations.DeleteModel( name='OrderProduct', ), migrations.AddField( model_name='basket', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='basket', to='foodcartapp.Order', verbose_name='Заказ'), ), migrations.AddField( model_name='basket', name='product', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='basket', to='foodcartapp.Product', verbose_name='Блюдо'), ), ]
class Donation(models.Model): guid = models.CharField(max_length=50) user = models.ForeignKey(User, null=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) company = models.CharField(max_length=50, default='', blank=True, null=True) address = models.CharField(max_length=100, default='', blank=True, null=True) address2 = models.CharField(_('address line 2'), max_length=100, default='', blank=True, null=True) city = models.CharField(max_length=50, default='', blank=True, null=True) state = models.CharField(max_length=50, default='', blank=True, null=True) zip_code = models.CharField(max_length=50, default='', blank=True, null=True) country = models.CharField(max_length=50, default='', blank=True, null=True) email = models.CharField(max_length=50) phone = models.CharField(max_length=50) referral_source = models.CharField(_('referred by'), max_length=200, default='', blank=True, null=True) comments = models.TextField(blank=True, null=True) donation_amount = models.DecimalField(max_digits=10, decimal_places=2) allocation = models.CharField(max_length=150, default='', blank=True, null=True) payment_method = models.CharField(max_length=50, default='cc') invoice = models.ForeignKey(Invoice, blank=True, null=True) create_dt = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey(User, null=True, related_name="donation_creator") creator_username = models.CharField(max_length=50, null=True) owner = models.ForeignKey(User, null=True, related_name="donation_owner") owner_username = models.CharField(max_length=50, null=True) status_detail = models.CharField(max_length=50, default='estimate') status = models.NullBooleanField(default=True) objects = DonationManager() class Meta: app_label = 'donations' def save(self, user=None, *args, **kwargs): if not self.id: self.guid = str(uuid.uuid1()) if user and user.id: self.creator=user self.creator_username=user.username if user and user.id: self.owner=user self.owner_username=user.username super(Donation, self).save(*args, **kwargs) # Called by payments_pop_by_invoice_user in Payment model. def get_payment_description(self, inv): """ The description will be sent to payment gateway and displayed on invoice. If not supplied, the default description will be generated. """ return 'Tendenci Invoice %d Payment for Donation %d' % ( inv.id, inv.object_id, ) def make_acct_entries(self, user, inv, amount, **kwargs): """ Make the accounting entries for the donation sale """ from tendenci.apps.accountings.models import Acct, AcctEntry, AcctTran from tendenci.apps.accountings.utils import make_acct_entries_initial, make_acct_entries_closing ae = AcctEntry.objects.create_acct_entry(user, 'invoice', inv.id) if not inv.is_tendered: make_acct_entries_initial(user, ae, amount) else: # payment has now been received make_acct_entries_closing(user, ae, amount) # #CREDIT donation SALES acct_number = self.get_acct_number() acct = Acct.objects.get(account_number=acct_number) AcctTran.objects.create_acct_tran(user, ae, acct, amount*(-1)) def get_acct_number(self, discount=False): if discount: return 465100 else: return 405100 def auto_update_paid_object(self, request, payment): """ Update the object after online payment is received. """ # email to admin try: from tendenci.apps.notifications import models as notification except: notification = None from tendenci.apps.perms.utils import get_notice_recipients recipients = get_notice_recipients('module', 'donations', 'donationsrecipients') if recipients: if notification: extra_context = { 'donation': self, 'invoice': payment.invoice, 'request': request, } notification.send_emails(recipients,'donation_added', extra_context)
class Migration(migrations.Migration): initial = True dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.CreateModel( name='Predictions', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('age', models.IntegerField()), ('sex', models.IntegerField(choices=[(0, 'Female'), (1, 'Male')], default=0)), ('cp', models.IntegerField(choices=[(1, 'Typical Angina'), (2, 'Atypical Angina'), (3, 'Non-Angina'), (4, 'Asymptomatic')], default=1)), ('resting_bp', models.IntegerField()), ('serum_cholesterol', models.IntegerField()), ('fasting_blood_sugar', models.IntegerField(choices=[(1, 'true'), (2, 'false')], default=0)), ('resting_ecg', models.IntegerField(choices=[(0, 'Normal'), (1, 'Having ST-T wave abnormality'), (2, 'hypertrophy')], default=0)), ('max_heart_rate', models.IntegerField()), ('exercise_induced_angina', models.IntegerField(choices=[(0, 'No'), (1, 'Yes')], default=0)), ('st_depression', models.DecimalField(decimal_places=2, max_digits=4)), ('st_slope', models.IntegerField( choices=[(1, 'Upsloping'), (2, 'Flat'), (3, 'Down Sloping')])), ('number_of_vessels', models.IntegerField( choices=[(0, 'None'), (1, 'One'), (2, 'Two'), (3, 'Three')])), ('thallium_scan_results', models.IntegerField(choices=[(3, 'Normal'), ( 6, 'Fixed Defect'), (7, 'Reversible Defect')])), ('predicted_on', models.DateTimeField(default=django.utils.timezone.now)), ('num', models.IntegerField()), ('profile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='predict', to='accounts.UserProfileInfo')), ], ), ]
class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Ingredient', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('name', models.CharField(max_length=255, unique=True)), ('logo', models.ImageField(upload_to='stores')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Store', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('name', models.CharField(max_length=255, unique=True)), ('description', models.TextField()), ('logo', models.ImageField(upload_to='stores')), ('delivery_fee', models.DecimalField(decimal_places=2, default=0.0, max_digits=5)), ('profit_fee', models.DecimalField(decimal_places=2, default=0.0, max_digits=5)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='StoreIngredients', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('stock', models.IntegerField(default=0)), ('price', models.DecimalField(decimal_places=2, default=0.0, max_digits=5)), ('ingredient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='stores.ingredient')), ('store', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='stores.store')), ], options={ 'abstract': False, }, ), migrations.AddField( model_name='store', name='ingredients', field=models.ManyToManyField(related_name='stores', through='stores.StoreIngredients', to='stores.Ingredient'), ), migrations.AddField( model_name='store', name='owner', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
class DecimalFieldModel(models.Model): decimal_field = models.DecimalField( max_digits=3, decimal_places=1, validators=[MinValueValidator(1), MaxValueValidator(3)] )
class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Laptop', fields=[ ('code', models.IntegerField(primary_key=True, serialize=False)), ('speed', models.SmallIntegerField()), ('ram', models.SmallIntegerField()), ('hd', models.FloatField()), ('price', models.DecimalField(blank=True, decimal_places=2, max_digits=12, null=True)), ('screen', models.SmallIntegerField()), ], ), migrations.CreateModel( name='Pc', fields=[ ('code', models.IntegerField(primary_key=True, serialize=False)), ('speed', models.SmallIntegerField()), ('ram', models.SmallIntegerField()), ('hd', models.FloatField()), ('cd', models.CharField(max_length=10)), ('price', models.DecimalField(blank=True, decimal_places=2, max_digits=12, null=True)), ], ), migrations.CreateModel( name='Printer', fields=[ ('code', models.IntegerField(primary_key=True, serialize=False)), ('color', models.CharField(max_length=1)), ('type', models.CharField(max_length=10)), ('price', models.DecimalField(blank=True, decimal_places=2, max_digits=12, null=True)), ], ), migrations.CreateModel( name='Product', fields=[ ('maker', models.CharField(max_length=10)), ('model', models.CharField(max_length=50, primary_key=True, serialize=False)), ('type', models.CharField(max_length=50)), ], ), migrations.AddField( model_name='printer', name='model', field=models.ForeignKey(db_column='model', on_delete=django.db.models.deletion.DO_NOTHING, to='comp_info.Product'), ), migrations.AddField( model_name='pc', name='model', field=models.ForeignKey(db_column='model', on_delete=django.db.models.deletion.DO_NOTHING, to='comp_info.Product'), ), migrations.AddField( model_name='laptop', name='model', field=models.ForeignKey(db_column='model', on_delete=django.db.models.deletion.DO_NOTHING, to='comp_info.Product'), ), ]
class AbstractStockRecord(models.Model): """ A stock record. This records information about a product from a fulfilment partner, such as their SKU, the number they have in stock and price information. Stockrecords are used by 'strategies' to determine availability and pricing information for the customer. """ product = models.ForeignKey('catalogue.Product', on_delete=models.CASCADE, related_name="stockrecords", verbose_name=_("Product")) partner = models.ForeignKey('partner.Partner', on_delete=models.CASCADE, verbose_name=_("Partner"), related_name='stockrecords') #: The fulfilment partner will often have their own SKU for a product, #: which we store here. This will sometimes be the same the product's UPC #: but not always. It should be unique per partner. #: See also http://en.wikipedia.org/wiki/Stock-keeping_unit partner_sku = models.CharField(_("Partner SKU"), max_length=128) # Price info: price_currency = models.CharField(_("Currency"), max_length=12, default=get_default_currency) # This is the base price for calculations - tax should be applied by the # appropriate method. We don't store tax here as its calculation is highly # domain-specific. It is NULLable because some items don't have a fixed # price but require a runtime calculation (possible from an external # service). Current field name `price_excl_tax` is deprecated and will be # renamed into `price` in Oscar 2.0. price_excl_tax = models.DecimalField(_("Price (excl. tax)"), decimal_places=2, max_digits=12, blank=True, null=True) # Deprecated - will be removed in Oscar 2.0 price_retail = models.DecimalField(_("Price (retail)"), decimal_places=2, max_digits=12, blank=True, null=True) # Deprecated - will be removed in Oscar 2.0 cost_price = models.DecimalField(_("Cost Price"), decimal_places=2, max_digits=12, blank=True, null=True) #: Number of items in stock num_in_stock = models.PositiveIntegerField(_("Number in stock"), blank=True, null=True) #: The amount of stock allocated to orders but not fed back to the master #: stock system. A typical stock update process will set the num_in_stock #: variable to a new value and reset num_allocated to zero num_allocated = models.IntegerField(_("Number allocated"), blank=True, null=True) #: Threshold for low-stock alerts. When stock goes beneath this threshold, #: an alert is triggered so warehouse managers can order more. low_stock_threshold = models.PositiveIntegerField(_("Low Stock Threshold"), blank=True, null=True) # Date information date_created = models.DateTimeField(_("Date created"), auto_now_add=True) date_updated = models.DateTimeField(_("Date updated"), auto_now=True, db_index=True) def __str__(self): msg = u"Partner: %s, product: %s" % ( self.partner.display_name, self.product, ) if self.partner_sku: msg = u"%s (%s)" % (msg, self.partner_sku) return msg class Meta: abstract = True app_label = 'partner' unique_together = ('partner', 'partner_sku') verbose_name = _("Stock record") verbose_name_plural = _("Stock records") @property def net_stock_level(self): """ The effective number in stock (eg available to buy). This is correct property to show the customer, not the num_in_stock field as that doesn't account for allocations. This can be negative in some unusual circumstances """ if self.num_in_stock is None: return 0 if self.num_allocated is None: return self.num_in_stock return self.num_in_stock - self.num_allocated @cached_property def can_track_allocations(self): """Return True if the Product is set for stock tracking.""" return self.product.product_class.track_stock # 2-stage stock management model def allocate(self, quantity): """ Record a stock allocation. This normally happens when a product is bought at checkout. When the product is actually shipped, then we 'consume' the allocation. """ # Doesn't make sense to allocate if stock tracking is off. if not self.can_track_allocations: return # Send the pre-save signal signals.pre_save.send(sender=self.__class__, instance=self, created=False, raw=False, using=router.db_for_write(self.__class__, instance=self)) # Atomic update (self.__class__.objects.filter(pk=self.pk).update( num_allocated=(Coalesce(F('num_allocated'), Value(0)) + quantity))) # Make sure the current object is up-to-date if self.num_allocated is None: self.num_allocated = 0 self.num_allocated += quantity # Send the post-save signal signals.post_save.send(sender=self.__class__, instance=self, created=False, raw=False, using=router.db_for_write(self.__class__, instance=self)) allocate.alters_data = True def is_allocation_consumption_possible(self, quantity): """ Test if a proposed stock consumption is permitted """ return quantity <= min(self.num_allocated, self.num_in_stock) def consume_allocation(self, quantity): """ Consume a previous allocation This is used when an item is shipped. We remove the original allocation and adjust the number in stock accordingly """ if not self.can_track_allocations: return if not self.is_allocation_consumption_possible(quantity): raise InvalidStockAdjustment( _('Invalid stock consumption request')) self.num_allocated -= quantity self.num_in_stock -= quantity self.save() consume_allocation.alters_data = True def cancel_allocation(self, quantity): if not self.can_track_allocations: return # We ignore requests that request a cancellation of more than the # amount already allocated. self.num_allocated -= min(self.num_allocated, quantity) self.save() cancel_allocation.alters_data = True @property def is_below_threshold(self): if self.low_stock_threshold is None: return False return self.net_stock_level < self.low_stock_threshold
class Migration(migrations.Migration): dependencies = [ ('app1', '0028_monthly_medical_script1_paper_code'), ] operations = [ migrations.AddField( model_name='mdeical_transform1', name='paper_code', field=models.CharField(default=uuid.uuid4, max_length=120), ), migrations.AddField( model_name='mdeical_transform2', name='cost_flag', field=models.BooleanField(default=False), ), migrations.AddField( model_name='mdeical_transform2', name='paper_code', field=models.CharField(default=uuid.uuid4, max_length=120), ), migrations.AddField( model_name='mdeical_transform2', name='trans_to', field=models.CharField(blank=True, choices=[('عيادة', 'عيادة'), ('معمل', 'معمل'), ('مستشفى', 'مستشفى')], max_length=120, null=True, verbose_name='التحويل الـى'), ), migrations.AddField( model_name='mdeical_transform2', name='transform_cost', field=models.DecimalField(blank=True, decimal_places=3, default=Decimal('0.000'), max_digits=19, null=True, verbose_name='تكلفة التحويل الطبى'), ), migrations.AddField( model_name='mdeical_transform3', name='paper_code', field=models.CharField(default=uuid.uuid4, max_length=120), ), migrations.AddField( model_name='mdeical_transform3', name='trans_to', field=models.CharField(blank=True, choices=[('عيادة', 'عيادة'), ('معمل', 'معمل'), ('مستشفى', 'مستشفى')], max_length=120, null=True, verbose_name='التحويل الـى'), ), migrations.AddField( model_name='mdeical_transform3', name='transform_cost', field=models.DecimalField(blank=True, decimal_places=3, default=Decimal('0.000'), max_digits=19, null=True, verbose_name='تكلفة التحويل الطبى'), ), migrations.AddField( model_name='medical_script1', name='paper_code', field=models.CharField(default=uuid.uuid4, max_length=120), ), migrations.AddField( model_name='medical_script2', name='paper_code', field=models.CharField(default=uuid.uuid4, max_length=120), ), migrations.AddField( model_name='medical_script2', name='total_medic_cost', field=models.DecimalField(blank=True, decimal_places=3, default=Decimal('0.000'), max_digits=19, null=True, verbose_name='إجمالى التكاليف '), ), migrations.AddField( model_name='medical_script2', name='updated', field=models.DateField(auto_now_add=True, null=True), ), migrations.AddField( model_name='medical_script3', name='paper_code', field=models.CharField(default=uuid.uuid4, max_length=120), ), migrations.AddField( model_name='medical_script3', name='total_medic_cost', field=models.DecimalField(blank=True, decimal_places=3, default=Decimal('0.000'), max_digits=19, null=True, verbose_name='إجمالى التكاليف '), ), migrations.AddField( model_name='monthly_medical_script2', name='Added', field=models.BooleanField(default=False), ), migrations.AddField( model_name='monthly_medical_script2', name='master', field=models.BooleanField(default=False), ), migrations.AddField( model_name='monthly_medical_script2', name='paper_code', field=models.CharField(default=uuid.uuid4, max_length=120), ), migrations.AddField( model_name='monthly_medical_script2', name='total_cost', field=models.DecimalField(blank=True, decimal_places=3, default=Decimal('0.000'), max_digits=19, null=True, verbose_name='تكلفة علاج رقم 20'), ), migrations.AddField( model_name='monthly_medical_script3', name='Added', field=models.BooleanField(default=False), ), migrations.AddField( model_name='monthly_medical_script3', name='master', field=models.BooleanField(default=False), ), migrations.AddField( model_name='monthly_medical_script3', name='paper_code', field=models.CharField(default=uuid.uuid4, max_length=120), ), migrations.AddField( model_name='monthly_medical_script3', name='total_cost', field=models.DecimalField(blank=True, decimal_places=3, default=Decimal('0.000'), max_digits=19, null=True, verbose_name='تكلفة علاج رقم 20'), ), migrations.AlterField( model_name='mdeical_transform2', name='auth_doc', field=models.CharField(choices=[('محمد', 'محمد'), ('', ''), ('', ''), ('', ''), ('', '')], max_length=120, verbose_name='طبيب العيادة '), ), ]