summaryrefslogtreecommitdiff
path: root/app/ebay/models.py
blob: 4338197b8a85bdde06d40a497c4991208d868ec7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import datetime 
import re
from django.contrib.gis.db import models
from bs4 import BeautifulSoup
import requests

class Item(models.Model):
    name = models.CharField(max_length=200)
    purchase_price = models.IntegerField()
    url = models.CharField(max_length=200)
    currently_own = models.BooleanField(blank=True, default=False)
    sold = models.BooleanField(blank=True, default=False)
    sale_price = models.IntegerField()
    
    def save(self, **kwargs):
        super(Item, self).save()

    def __str__(self):
        return self.name
    

class TrackedItem(models.Model):
    url = models.CharField(max_length=200)
    title = models.CharField(max_length=200)
    
    def save(self, **kwargs):
        super(TrackedItem, self).save()

    @property
    def get_latest_price(self):
        return self.price_set.latest().price

    def __str__(self):
        return self.title


class Price(models.Model):
    date = models.DateTimeField(blank=True)
    price = models.DecimalField(max_digits=6, decimal_places=2)
    item = models.ForeignKey(TrackedItem)
    
    class Meta:
        ordering = ('-date',)
        get_latest_by = 'date'

    def __str__(self):
        return str(self.date)
    
    def save(self, **kwargs):
        if not self.pk:
            self.date = datetime.datetime.now()
        super(Price, self).save()


def update_tracked_item_price(item):
    r = requests.get(item.url)
    soup = BeautifulSoup(r.text, "lxml")
    numbers = re.compile('\d+(?:\.\d+)?')
    price = soup.find(itemprop="price").get_text()
    price = numbers.findall(price)[0]
    l, created = Price.objects.get_or_create(
        price=price,
        item=item
    )