开发者

Django based marketplace, creating a transaction history

I'm trying to create a transaction history for each transaction on a Django based marketplace.

I thought the best way of keeping track of this data was to override the save() function and create a Transaction record.

class Transaction(models.Model):
    item = models.ManyToManyField(Item, blank=True)开发者_运维技巧
    buyer = models.ManyToManyField(User, related_name='buyer')
    seller = models.ManyToManyField(User, related_name='seller')
    description = models.CharField(max_length=500)
    purchase_date = models.DateField(auto_now_add=True)
    value = models.DecimalField(max_digits=7, decimal_places=2)
    def save(self, *args, **kwargs):
        self.buyer.money+=self.value
        self.seller.money-=self.value
        super(Transaction, self).save(*args, **kwargs)

Am I going about this all wrong? Currenlty I get...

'Transaction' instance needs to have a primary key value before a many-to-many relationship can be used.


  1. You have to save your object before you can go through many-to-many relationships.

  2. Please explain how you can have multiple buyers and sellers on a single transaction. (For the rest of this answer, I'm assuming that there aren't and you meant for these to be ForeignKey fields.)

  3. The related names for buyer and seller are not clear. See below.

  4. I'm not sure what description is for. Is it different from the item list?

  5. item should be called items, since it can be plural, and you might want to create a custom junction table (using the "through" parameter) with a quantity field.

  6. You forgot to save the related objects.

Modified version:

class Transaction(models.Model):
    items = models.ManyToManyField(Item, through='TransactionItem', blank=True)
    buyer = models.ForeignKey(User, related_name='transactions_as_buyer')
    seller = models.ForeignKey(User, related_name='transactions_as_seller')
    description = models.CharField(max_length=500)
    purchase_date = models.DateField(auto_now_add=True)
    value = models.DecimalField(max_digits=7, decimal_places=2)

    def save(self, *args, **kwargs):
        super(Transaction, self).save(*args, **kwargs)
        self.buyer.money += self.value
        self.buyer.save()
        self.seller.money -= self.value
        self.seller.save()

class TransactionItem(models.Model):
    transaction = models.ForeignKey(Transaction)
    item = models.ForeignKey(Item)
    quantity = models.IntegerField()


The buyer and seller fields are many to many fields so self.buyer will never work, I think you were meaning to use ForeignKey instead of ManyToManyField.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜