Ticket #34141: models.py

File models.py, 1.2 KB (added by Jeremy Nix, 2 years ago)
Line 
1from django.db import models
2
3class Company(models.Model):
4 name = models.TextField(max_length=500, unique=True, verbose_name='Company Name')
5 locations = models.ManyToManyField(Location, through="CompanyLocation")
6 record_status = models.TextField(max_length=25, unique=True, verbose_name='Record Status')
7
8class Location(models.Model):
9 name = models.TextField(max_length=500, unique=True, verbose_name='Location Name')
10 record_status = models.TextField(max_length=25, unique=True, verbose_name='Record Status')
11
12class CompanyLocation(models.Model):
13 company = models.ForeignKey(Company, on_delete=models.CASCADE)
14 location = models.ForeignKey(
15 Location, on_delete=models.CASCADE, related_name="companies"
16 )
17 record_status = models.TextField(max_length=25, unique=True, verbose_name='Record Status')
18
19 class Meta:
20 unique_together = ["company", "location"]
21
22
23# QuerySet w/ Prefetch Example:
24queryset = (
25 models.Company.objects
26 .prefetch_related(
27 # Only active Locations
28 Prefetch(
29 "locations",
30 queryset=models.Location.filter(record_status="Active")
31 .extra(where=["demo_companylocation.record_status='Active'"]),
32 ),
33 )
34 .all()
35 # Only active Companies
36 .filter(record_status="Active")
37 .order_by("name")
38)
Back to Top