Skip to content

Instantly share code, notes, and snippets.

@code-shoily
Created October 5, 2019 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-shoily/562b691760471114ee00bc404a96eef0 to your computer and use it in GitHub Desktop.
Save code-shoily/562b691760471114ee00bc404a96eef0 to your computer and use it in GitHub Desktop.
import datetime
from typing import Dict, Any
from hypothesis import strategies
from django.db import models
from django.db.models import F, When, Case
class MessageManager(models.Manager):
def latest_distinct(self):
return super().get_queryset().annotate(
user_1=Case(
When(sender__gt=F('recipient'), then=F('recipient')),
default=F('sender')
),
user_2=Case(
When(sender__gt=F('recipient'), then=F('sender')),
default=F('recipient')
)
).order_by('user_1', 'user_2', '-when').distinct('user_1', 'user_2')
class Message(models.Model):
when = models.DateTimeField(auto_now=True, db_index=True)
sender = models.CharField(max_length=127)
recipient = models.CharField(max_length=127)
objects = MessageManager()
def __str__(self):
return f'[{self.when.ctime()}] {self.sender} -> {self.recipient}'
def example_message() -> Dict[str, Any]:
users = [
'batman', 'superman', 'wonder-woman', 'flash', 'green-lantern', 'martian-manhunter',
'joker', 'darkseid', 'lex-luthor', 'ananta-jalil', 'zoom', 'savitr', 'mr-mxyzpltk',
'victor-zsasz', 'hawkgirl', 'guardian', 'super-girl',
]
sender = strategies.sampled_from(users).example()
recipient = strategies.sampled_from([u for u in users if u != sender]).example()
when = strategies.dates(min_value=datetime.date(2019, 1, 1),
max_value=datetime.date.today()).example()
return {
'sender': sender,
'recipient': recipient,
'when': when
}
def seed(limit: int = 1000) -> None:
for _ in range(limit):
Message.objects.create(**example_message())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment