class meta 3a unique together 3d 28 27category name 27 2c 29

Solutions on MaxInterview for class meta 3a unique together 3d 28 27category name 27 2c 29 by the best coders in the world

showing results for - "class meta 3a unique together 3d 28 27category name 27 2c 29"
Gaia
27 Jun 2020
1class Category(models.Model):
2    name = models.CharField(max_length=200)
3    slug = models.SlugField()
4    parent = models.ForeignKey('self',blank=True, null=True ,related_name='children')
5
6    class Meta:
7        #enforcing that there can not be two categories under a parent with same slug
8        
9        # __str__ method elaborated later in post.  use __unicode__ in place of
10        
11        # __str__ if you are using python 2
12
13        unique_together = ('slug', 'parent',)    
14        verbose_name_plural = "categories"     
15
16    def __str__(self):                           
17        full_path = [self.name]                  
18        k = self.parent
19        while k is not None:
20            full_path.append(k.name)
21            k = k.parent
22        return ' -> '.join(full_path[::-1])