使用其他月份的对象填充空白月份

时间:2014-12-15 10:18:52

标签: python django

我有一个产品清单,以及每种产品的连接价格表。我已经导入了一些数据来填充每个月的价目表,但是有一个月缺失了,我想根据published_frompublished_to

我的models.py

class Product(models.Model):
    name = models.CharField(max_length=500, blank=True, null=True)  
    product_id = models.IntegerField(blank=True, null=True)



class Price(models.Model):
    product = models.ForeignKey(Product)
    price = models.FloatField()
    date_saved = models.DateTimeField()
    published_from = models.DateTimeField(blank=True, null=True)
    published_to = models.DateTimeField(blank=True, null=True)

这是我尝试过的,但我没有收到任何错误,也没有创建任何新价格。

def fill_in_blanks_prices(request):

    product_list = Product.objects.all()
    month_list = [[datetime(2014, i, 1)] for i in xrange(1, 13)]


    #Loop through every product  
    for product in product_list:

        #Loop through every month
        for month in month_list:

            #Month returns a list with one datetime object
            for item in month:
                naive = item
                current_month = pytz.timezone("Europe/Oslo").localize(naive, is_dst=None)

                try:
                    price = Price.objects.filter(product=product, date_saved=current_month)
                    #Price found, do nothing
                    pass

                 except Price.DoesNotExist:
                    #Price in the given month not found
                    #Find a price that is published_from greater than current month and published_to less than current month

                    try:
                        other_price = Price.objects.filter(product=product, published_from__gte=current_month, published_to__lte=current_month)[:1]

                        #Duplicate the other_price
                        for object in other_price:
                            object.id = None
                            object.date_saved__month = current_month
                            object.save()

                    except Price.DoesNotExist:
                        #No matching price
                        pass

    return HttpResponse("Processing")

任何人都能看到我做错了什么?

编辑:

我发现了错误:

RuntimeWarning: DateTimeField Price.date_saved received a naive datetime (2014-12-01 00:00:00) while time zone support is active.

编辑2:

我将日期时间转换为不天真,但我仍然无法创造新价格。

0 个答案:

没有答案