You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django模型字段选型:交易表用ForeignKey还是OneToOneField?

Django Transaction Table: ForeignKey vs OneToOneField Breakdown

Great question! Let's break this down based on how each entity relates to your new transaction table—let's call it StockTransaction for clarity.

Field Type Decisions

Let’s map each required field to the correct Django relationship type:

  • Seller ID: A single seller can have multiple transactions (they might sell the same stock to different buyers, or list multiple stocks over time). Since one seller links to many transactions, this should be a ForeignKey to the User model.
  • Buyer ID: Similarly, a single buyer can make multiple purchases (buying different stocks from various sellers, or re-buying the same stock later). One buyer links to many transactions, so this is also a ForeignKey to User.
  • Stock ID: A single stock listing can be bought multiple times (assuming the seller has multiple shares available). One stock links to many transactions, so this needs to be a ForeignKey to the Stocks model.

When to Use OneToOneField?

You’d only use OneToOneField if the relationship was strictly one-to-one—like if a seller could only ever make one transaction, or a stock could only be sold once. That doesn’t fit your use case here, since buyers and sellers will likely have multiple transactions over time, and stocks can be sold repeatedly.

Example Model Code

Here’s how you’d implement this in Django:

from django.db import models
from django.contrib.auth.models import User

class Stocks(models.Model):
    # Your existing Stocks fields
    ticker = models.CharField(max_length=10)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    available_quantity = models.IntegerField()
    # ... add other fields as needed

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # Your existing UserProfile fields (e.g., contact info, billing address)
    # ... add other fields as needed

class StockTransaction(models.Model):
    seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sold_transactions")
    buyer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="purchased_transactions")
    stock = models.ForeignKey(Stocks, on_delete=models.CASCADE, related_name="transaction_history")
    transaction_date = models.DateTimeField(auto_now_add=True)
    purchased_quantity = models.IntegerField()
    final_price = models.DecimalField(max_digits=10, decimal_places=2)
    # ... add other transaction-specific fields

The related_name arguments make it easy to query related data later—for example, user.sold_transactions.all() will return all sales made by a specific seller.

内容的提问来源于stack exchange,提问作者Za Gol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:05:10