-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
218 lines (178 loc) · 6.87 KB
/
models.py
File metadata and controls
218 lines (178 loc) · 6.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import hashlib
import hmac
import math
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
class User(AbstractUser):
"""
This extends the User model from django-labs-account
to add phonenumber related fields
"""
phone_number = PhoneNumberField(null=True, blank=True)
phone_verified = models.BooleanField(default=False)
phone_verified_at = models.DateTimeField(null=True, blank=True)
class Offer(models.Model):
class Meta:
constraints = [
models.UniqueConstraint(
fields=["user", "listing"], name="unique_offer_market"
)
]
indexes = [
models.Index(fields=["user"]),
models.Index(fields=["listing"]),
models.Index(fields=["created_at"]),
]
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="offers")
listing = models.ForeignKey(
"Listing", on_delete=models.CASCADE, related_name="offers_received"
)
offered_price = models.DecimalField(
max_digits=10, decimal_places=2, validators=[MinValueValidator(0)]
)
message = models.TextField(max_length=500, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Offer for {self.listing} made by {self.user}"
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
class Meta:
verbose_name_plural = "Categories"
def __str__(self):
return self.name
class Tag(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Listing(models.Model):
class Meta:
indexes = [
models.Index(fields=["title"]),
models.Index(fields=["price"]),
models.Index(fields=["created_at"]),
models.Index(fields=["expires_at"]),
models.Index(fields=["negotiable"]),
]
seller = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="listings_created"
)
buyers = models.ManyToManyField(
User, through=Offer, related_name="listings_offered", blank=True
)
tags = models.ManyToManyField(Tag, blank=True)
favorites = models.ManyToManyField(
User, related_name="listings_favorited", blank=True
)
title = models.CharField(max_length=255)
description = models.TextField(null=True, blank=True)
external_link = models.URLField(max_length=255, null=True, blank=True)
price = models.DecimalField(
max_digits=10, decimal_places=2, validators=[MinValueValidator(0)]
)
negotiable = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
expires_at = models.DateTimeField(null=True, blank=True)
def __str__(self):
return f"{self.title} by {self.seller}"
class ListingImage(models.Model):
listing = models.ForeignKey(
Listing, on_delete=models.CASCADE, related_name="images"
)
image = models.ImageField(upload_to="marketplace/images")
order = models.PositiveIntegerField(default=0)
class Meta:
ordering = ["order"]
def __str__(self):
return f"Image for {self.listing}"
class Item(Listing):
class Condition(models.TextChoices):
NEW = "NEW", "New"
LIKE_NEW = "LIKE_NEW", "Used - Like New"
GOOD = "GOOD", "Used - Good"
FAIR = "FAIR", "Used - Fair"
condition = models.CharField(
max_length=50, choices=Condition.choices, default=Condition.NEW
)
category = models.ForeignKey(
Category, on_delete=models.PROTECT, related_name="items"
)
class Sublet(Listing):
street_address = models.CharField(max_length=255)
beds = models.PositiveIntegerField()
baths = models.PositiveIntegerField()
start_date = models.DateField()
end_date = models.DateField()
latitude = models.FloatField(null=True, blank=True)
longitude = models.FloatField(null=True, blank=True)
def clean(self):
super().clean()
if self.start_date and self.end_date and self.start_date >= self.end_date:
raise ValidationError({"end_date": "End date must be after start date"})
def _calculate_approximate_location(self, latitude, longitude):
if latitude is None or longitude is None:
return None, None
lat_str = f"{float(latitude):.9f}"
lon_str = f"{float(longitude):.9f}"
seed = hmac.new(
settings.SECRET_KEY.encode(),
f"{lat_str}{lon_str}".encode(),
hashlib.sha256,
).hexdigest()
offset_factor = int(seed[:8], 16) / 0xFFFFFFFF
offset_distance = 0.0005 + (offset_factor * 0.0013)
angle = offset_factor * 2 * math.pi
lat_offset = offset_distance * math.sin(angle)
lon_offset = offset_distance * math.cos(angle)
approx_lat = float(latitude) + lat_offset
approx_lon = float(longitude) + lon_offset
return approx_lat, approx_lon
@property
def approximate_location(self):
if self.latitude is not None and self.longitude is not None:
approximate_location = self._calculate_approximate_location(
self.latitude, self.longitude)
return approximate_location
return None, None
def save(self, *args, **kwargs):
self.full_clean()
super().save(*args, **kwargs)
class Rating(models.Model):
class RatingType(models.TextChoices):
BUYER = "BUYER", "Buyer Rating"
SELLER = "SELLER", "Seller Rating"
class Meta:
constraints = [
models.UniqueConstraint(
fields=["reviewer", "reviewed_user", "listing"],
name="unique_rating_market",
)
]
indexes = [
models.Index(fields=["reviewer"]),
models.Index(fields=["reviewed_user"]),
models.Index(fields=["listing"]),
models.Index(fields=["created_at"]),
]
reviewer = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="ratings_given"
)
reviewed_user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="ratings_received"
)
listing = models.ForeignKey(
Listing, on_delete=models.CASCADE, related_name="ratings"
)
score = models.PositiveIntegerField(
validators=[MinValueValidator(1), MaxValueValidator(5)]
)
rating_type = models.CharField(
max_length=10, choices=RatingType.choices, default=RatingType.BUYER
)
comment = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Rating of {self.score} for {self.reviewed_user} by {self.reviewer}"