Django Unique ID [英] Django Unique Slug by id

查看:145
本文介绍了Django Unique ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



class Deal(models.Model):
title = models.CharField(max_length = 75)

class
product = models.ForeignKey(Product)
slug = models.SlugField(max_length = 255,unique = True)

与上述类似的基本设置,我想为每个交易实例生成独特的s instance,使用交易本身的交易和编号的产品标题。 IE:apple-iphone-4s-161其中 161 是交易的ID,之前的文字是



为此,如何覆盖交易模型的save()方法以应用?

解决方案

当然,您可以简单地覆盖模型上的save()方法(或者为post_save信号制作接收器)。
它将是这样的:

 从django.template.defaultfilters导入slugify 

class deal(models.Model):
product = models.ForeignKey(Product)
slug = models.SlugField(max_length = 255,unique = True)

def save ,* args,** kwargs):
super(Deal,self).save(* args,** kwargs)
如果不是self.slug:
self.slug = slugify(self .product.title)+ - + str(self.id)
self.save()

但是,这个解决方案中的丑陋是它会打数据库两次(保存两次)。这是因为当创建新的交易对象时,它将不会有id,直到你第一次保存它(你不能做太多)。


class Product(models.Model):
    title = models.CharField(max_length=75)

class Deal(models.Model):
    product = models.ForeignKey(Product)
    slug = models.SlugField(max_length=255, unique=True)

Having a similar basic setup as above, I want to generate unique slugs for each Deal instance using product title of it's deal and id of the deal itself. IE: "apple-iphone-4s-161" where 161 is the id of the deal and the text before is the title of the product.

For this, how can I overwrite the save() method of the Deal model to apply it?

解决方案

Of course you can simply overwrite save() method on model (or make receiver for post_save signal). It will be something like:

from django.template.defaultfilters import slugify

class Deal(models.Model):
product = models.ForeignKey(Product)
slug = models.SlugField(max_length=255, unique=True)

    def save(self, *args, **kwargs):
        super(Deal, self).save(*args, **kwargs)
        if not self.slug:
            self.slug = slugify(self.product.title) + "-" + str(self.id)
            self.save()

But what is ugly in this solution is that it will hit database twice (it is saved two times). It is because when creating new Deal object it will not have id until you save it for the first time (and you cannot do much about it).

这篇关于Django Unique ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆