首页 > 解决方案 > 使用 INT django Python 连接字符串

问题描述

我有我的views.py

class ShopCreateView(CreateView):
    fields = ('shop_id',)
    model = models.Shop

    def form_valid(self, form):
        self.object = form.save(commit=False)

        dept_obj = models.departemen.objects.get(seller_id=self.object.id)
        dept_name = dept_obj.name

        date = datetime.datetime.now().date()
        year = date.year
        month = date.month

        seller_count = seller_obj.count()

        if seller_count > 999:
            counted = seller_count - 999

        self.object.shop_id = dept_name + join_date + year + month + counted
        self.object.save()


        return super(ModelFormMixin, self).form_valid(form)

这是我的解释

dept_name返回字符串

例如。

PT。柜台Avenger Manequin = CAM _

P T.国际工作= PIJ

我希望我的代码采用字母的第一个字符。但现在不知道该怎么做。找到解决方案,但它仅用于展示template.html

所以self.object.shop_id = dept_name + year + month + counted会喜欢:

CAM71804001

它的混合字符串和整数。如果 return也最后3har 1。我需要成功001

谢谢你!

标签: pythondjangodjango-views

解决方案


改为使用str.format。要选择字符串的第一个字母,只需用[0]. 您可以{:03}使用三个零传递到零填充,就像这样

self.object.shop_id = "{}{}{}{}{:03}".format(dept_name[0], join_date, year , month, counted)

推荐阅读