Skip to content

Commit

Permalink
Aplastar Bichinho
Browse files Browse the repository at this point in the history
- Add missing database constraint on TradeHistory
- Cleanup of unnecessary parameters
  • Loading branch information
math-a3k committed Aug 28, 2023
1 parent 88d6b29 commit e9aba14
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Generated by Django 4.2.4 on 2023-08-28 02:42

from django.db import migrations, models


def remove_duplicates(apps, schema_editor):
"""
Remvos duplicates on the (user, bot, timestart_key) if
they exists.
"""
TradeHistory = apps.get_model("base", "TradeHistory")
dups = (
TradeHistory.objects.all()
.order_by()
.annotate(
key=models.functions.Concat(
models.F("user"),
models.Value("--"),
models.F("bot"),
models.Value("--"),
models.F("timestamp_start"),
output_field=models.CharField(),
)
)
.values("timestamp_start", "key")
.annotate(dup_count=models.Count("key"))
).filter(dup_count__gt=1)
for ts in dups:
records = TradeHistory.objects.filter(
timestamp_start=ts["timestamp_start"]
)
for record in records[1:]:
record.delete()


class Migration(migrations.Migration):
dependencies = [
("base", "0015_alter_traderobot_fund_quote_asset_initial"),
]

operations = [
migrations.RunPython(
code=remove_duplicates,
reverse_code=migrations.RunPython.noop,
),
migrations.AddConstraint(
model_name="tradehistory",
constraint=models.UniqueConstraint(
fields=("user", "bot", "timestamp_start"),
name="unique_user_bot_timestamp_start",
),
),
]
7 changes: 6 additions & 1 deletion base/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2024,7 +2024,6 @@ def log(self, action, message=None):

def log_trade(self, cancelled=False):
trade_history, _ = self.trades.update_or_create(
bot=self,
user=self.user,
timestamp_start=self.timestamp_start,
defaults={
Expand Down Expand Up @@ -2419,6 +2418,12 @@ class Meta:
indexes = [
models.Index(fields=["-timestamp_selling"]),
]
constraints = [
models.UniqueConstraint(
fields=["user", "bot", "timestamp_start"],
name="unique_user_bot_timestamp_start",
)
]

objects = TradeHistoryManager()

Expand Down

0 comments on commit e9aba14

Please sign in to comment.