-
-
Notifications
You must be signed in to change notification settings - Fork 390
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Function as insert value #1680
Comments
You can do it this way: from __future__ import annotations
import datetime
from tortoise import Model, fields, run_async
from tortoise.contrib.test import init_memory_sqlite
class LinkedinLogging(Model):
class Meta:
table = "linkedin_logging"
id = fields.IntField(pk=True)
date = fields.DateField(unique=True)
withdraw = fields.IntField(default=0)
connections = fields.IntField(default=0)
whatsapp = fields.IntField(default=0)
like = fields.IntField(default=0)
@classmethod
async def get_no_duplicate_value(cls, field: str, value: int) -> int:
already: list[int] = (
await LinkedinLogging.filter(**{f"{field}__gte": value}) # type:ignore[assignment]
.order_by(field)
.values_list(field, flat=True)
)
if not already:
return value
for avail, used in zip(range(value, len(already) + value + 1), already):
if avail != used:
return avail
else:
return used + 1
@init_memory_sqlite
async def main():
columns = "table.withdraw, table.connections, table.whatsapp, table.like"
cols = [i.split(".")[-1] for i in columns.split(",")]
values = [0, 1, 0, 0]
data = dict(zip(cols, values))
today = datetime.date.today()
field = "connections"
data[field] = await LinkedinLogging.get_no_duplicate_value(field, data[field])
obj = LinkedinLogging(date=today, **data)
await obj.save()
print(dict(obj))
# {'connections': 1, ...}
data[field] = await LinkedinLogging.get_no_duplicate_value(field, data[field])
obj2 = LinkedinLogging(date=today + datetime.timedelta(1), **data)
await obj2.save()
print(dict(obj2))
# {'connections': 2, ...}
data[field] = await LinkedinLogging.get_no_duplicate_value(field, data[field])
obj3 = LinkedinLogging(date=today + datetime.timedelta(2), **data)
await obj3.save()
print(dict(obj3))
# {'connections': 3, ...}
run_async(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
im trying to convert this code to tortoise
date is a unique
this is the table sql
whenever i run it i get
The text was updated successfully, but these errors were encountered: