Created
October 5, 2019 16:03
-
-
Save code-shoily/562b691760471114ee00bc404a96eef0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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