如何在ebay中将新数据添加到Django中的数据库?

时间:2016-06-02 08:33:37

标签: python django python-3.x

我正在使用python ebay-sdk库连接ebay api。

我想从ebay api获取一些案例并将其保存到数据库中。

我有一个这样的应用程序和模型:

class Case(models.Model):
    # case is not necessarily a listing (often O2M)
    STATUS = Choices('new', 'cancelled', 'active', 'taken_down', 'archived')

    name = models.CharField(max_length=512)
    when_created = models.DateTimeField(default=now, blank=True)
    user = models.ForeignKey(User)
    make = models.ForeignKey(Make)
    status = StatusField(default=STATUS.new)
    platform = models.ForeignKey(Platform, on_delete=models.CASCADE)
    listing_id = models.CharField(max_length=64)
    listing_owner = models.CharField(max_length=128)
    url = models.CharField(max_length=512)
    price = models.FloatField(blank=True, null=True)
    # for now currency as char is ok.
    currency = models.CharField(max_length=3, default='USD')
    quantity = models.IntegerField(default=1)
    when_listing_started = models.DateTimeField(blank=True, null=True)
    when_listing_ends = models.DateTimeField(blank=True, null=True)
    valid_days = models.IntegerField(blank=True, null=True)

    objects = models.Manager.from_queryset(CaseQueryset)()

    def __str__(self):
        return self.name

    @property
    def days_valid(self):
        created = self.when_created.replace(tzinfo=None)
        now = datetime.datetime.utcnow().replace(tzinfo=None)
        datetime.timedelta(6, 1)
        return (now - created).days

    def handle_sent_report(self):
        self._set_active_state()

    def handle_cancel(self):
        self._set_cancelled_state()

    def _set_active_state(self):
        if self.status != Case.STATUS.new:
            raise InvalidCaseStatus
        self.status = Case.STATUS.active
        self.save()

    def _set_cancelled_state(self):
        if self.status not in (Case.STATUS.new, Case.STATUS.active):
            raise InvalidCaseStatus
        self.status = Case.STATUS.cancelled
        self.save()

我创建了其他应用ebay-finderebay_find.py以便在易趣中找到汽车:

from ebaysdk.finding import Connection as Finding

from django.db import models

from cases.models import Case
from trademarks.models import Make


def ebay_find():
    pass

api = Finding(domain='svcs.sandbox.ebay.com', appid="MY_EBAY_APP_ID", config_file=None)
response = api.execute('findItemsAdvanced', {'keywords': 'Cadillac'})
items = response.dict()
items_list = items['searchResult'].get('item')

ebay_cases = []

for item in items_list:
    new_case = Case.objects.create(
        name=item['title'],
        platform="Ebay",
        listing_id=car["model"],
        url=item['viewItemURL'],
        price=item['sellingStatus']['currentPrice']['value'],
        currency=item['sellingStatus']['currentPrice']['_currencyId']
    )
    new_case.save()

我很困惑如何将这些数据从items_list添加到我的数据库,如Case。我必须采取像Case中所有相同的字段吗?我可以在创建对象上设置一些默认字段吗?

1 个答案:

答案 0 :(得分:0)

如果您希望以最少的麻烦保存数据,那么请使用相同的字段名称。

您有一个模型字段的示例,其中包含您自己代码中的默认值:

checkscore()

您还可以覆盖模型的save()方法:

currency = models.CharField(max_length=3, default='USD')