import datetime import re from django.contrib.gis.db import models from django.utils import timezone 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): title = models.CharField(max_length=200) url = models.CharField(max_length=200) DESIRE = ( (0, '1'), (1, '2'), (2, '3'), (3, '4'), (4, '5'), ) amount_desired = models.IntegerField(choices=DESIRE, default=0) date_ending = models.DateTimeField(default=timezone.now) class Meta: ordering = ('date_ending', 'amount_desired') get_latest_by = 'date_ending' @property def get_latest_price(self): return self.price_set.latest().price def admin_link(self): return force_text('View Auction page' % (self.url)) admin_link.allow_tags = True admin_link.short_description = 'Link' def __str__(self): return self.title def save(self, **kwargs): super(TrackedItem, self).save() 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 )