Coverage for location/models.py: 94%

35 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-10-24 19:06 +0000

1from django.db import models 

2from django.db.models import Q 

3from django_countries.fields import CountryField 

4from django.urls import reverse 

5from simple_history.models import HistoricalRecords 

6from django.contrib.auth.models import Group 

7from taggit.managers import TaggableManager 

8 

9from . import app_label 

10 

11 

12class LocationManager(models.Manager): 

13 def get_by_natural_key(self, name, country): 

14 return self.get(name=name, country=country) 

15 

16 

17class Model(models.Model): 

18 objects = LocationManager() 

19 history = HistoricalRecords() 

20 name = models.CharField(max_length=45) 

21 country = CountryField() 

22 

23 group = models.ForeignKey( 

24 Group, 

25 editable=False, 

26 blank=True, 

27 null=True, 

28 on_delete=models.PROTECT, 

29 related_name="locations", 

30 ) 

31 

32 tags = TaggableManager(blank=True, related_name="location_tags") 

33 

34 def __str__(self): 

35 if self.country: 

36 return "{} / {}".format(self.name, self.country) 

37 else: 

38 return "%s" % (self.name) 

39 

40 def natural_key(self): 

41 return (self.name, str(self.country)) 

42 

43 @classmethod 

44 def get_natural_key_fields(cls): 

45 return ["name", "country"] 

46 

47 @classmethod 

48 def get_natural_key_info(cls): 

49 return [("name", None), ("country", None)] 

50 

51 def get_absolute_url(self): 

52 

53 return reverse("%s:detail" % app_label, kwargs={"pk": self.pk}) 

54 

55 class Meta: 

56 db_table = "{}_{}".format("sm", app_label) 

57 constraints = [ 

58 models.UniqueConstraint( 

59 fields=["name", "country", "group"], 

60 name="unique_sm_location_name_country_group", 

61 ), 

62 # PostgreSQL treats NULLs as distinct, so the constraint above 

63 # cannot deduplicate global (group=NULL) rows. Keep reference 

64 # data globally unique with a partial constraint. 

65 models.UniqueConstraint( 

66 fields=["name", "country"], 

67 condition=Q(group__isnull=True), 

68 name="unique_sm_location_global_name_country", 

69 ), 

70 ]