Coverage for src/wishlists/models.py: 88%

17 statements  

« prev     ^ index     » next       coverage.py v7.9.2, created at 2025-08-04 12:59 +0300

1from django.contrib.contenttypes.models import ContentType 

2from django.contrib.contenttypes.fields import GenericForeignKey 

3 

4from django.db import models 

5from django.contrib.auth import get_user_model 

6 

7UserModel = get_user_model() 

8 

9 

10class Wishlist(models.Model): 

11 class Meta: 

12 unique_together = [ 

13 # Prevents authenticated users from adding the same item twice 

14 ('user', 'content_type', 'object_id'), 

15 ] 

16 

17 ordering = ['-created_at'] 

18 

19 created_at = models.DateTimeField( 

20 auto_now_add=True, 

21 ) 

22 

23 user = models.ForeignKey( 

24 to=UserModel, 

25 null=True, 

26 blank=True, 

27 on_delete=models.CASCADE, 

28 ) 

29 

30 # ForeignKey to ContentType for generic relationships 

31 # This allows the wishlist to work with any product type 

32 # CASCADE ensures wishlist items are deleted when content type is deleted 

33 content_type = models.ForeignKey( 

34 ContentType, 

35 on_delete=models.CASCADE, 

36 ) 

37 

38 object_id = models.PositiveIntegerField() 

39 

40 # GenericForeignKey to the actual product object 

41 # This creates a generic relationship to any model 

42 # Uses content_type and object_id to resolve the actual object 

43 product = GenericForeignKey( 

44 'content_type', 

45 'object_id', 

46 ) 

47 

48 def __str__(self): 

49 user_info = self.user.email 

50 return f'{user_info} - {self.product}'