将标题默认为字段组合

时间:2016-05-31 11:45:49

标签: django

我怎样才能加入两个CharFields,bhk和locality,中间有一些字符串来创建这样的帖子的默认标题

title='%s house in %s'%(bhk, locality)

并从中创建slug?

class Listing(models.Model):
    slug = models.SlugField(unique=True)
    title = models.CharField(max_length=100)
    post_date = models.DateField(auto_now_add=True, auto_now=False)
    locality = models.CharField(max_length=100)

    r='1RK'
    one_bhk='1BHK'
    two_bhk='2BHK'
    three_bhk='3BHK'
    three_plus_bhk= '3+BHK'
    room_choices = (
        (r,'1RK'),
        (one_bhk,'1BHK'),
        (two_bhk,'2BHK'),
        (three_bhk,'3BHK'),
        (three_plus_bhk,'3+BHK'))

    bhk = models.CharField(max_length=10, choices= room_choices, default= r )

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('list:detail', kwargs={'slug': self.slug})

    def create_slug (instance, new_slug=None):
        slug= slugify(instance.title)
        if new_slug is not None:
            slug = new_slug
        qs = Listing.objects.filter(slug=slug).order_by('-id')
        exists= qs.exists()
        if exists:
            new_slug = '%s-%s' %(slug, qs.first().id)
            return create_slug(instance, new_slug=new_slug)
        return slug

1 个答案:

答案 0 :(得分:1)

我会使用属性

class Listing(models.Model):
    slug = models.SlugField(unique=True)
    title = models.CharField(max_length=100)
    post_date = models.DateField(auto_now_add=True, auto_now=False)
    locality = models.CharField(max_length=100)

   @property
   def default_title(self):
       return '%s house in %s' % (self.title, self.locality)

   @property
   def default_slug(self):
       return '%s' % slugify(self.default_title)

属性的一个优点是您可以在模板中使用它,就像它是普通的类属性一样:

{{ listing.default_title }}