I'm designing a payment system for a website, but I have trouble. A person can do a Payment and that Payment has a payment type, for example, debit card, credit card or PayPal. So, I need the possibility to add new payment options. The problem is I don't know how to link these two tables, I know that I need a third table with only the payment_id and the payment_type_id assigned. Is there a way to generate this with Django?

class PaymentType(models.Model):
    """Payment option available"""
    name = models.CharField(unique=True, max_length=255)
    created_on = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

    def __str__(self):
        return self.name

class Payment(models.Model):
    class PaymentStatus(models.TextChoices):
        DONE = '1', "DONE"
        PENDENT = '2', "PENDENT"
        CANCELED = '3', "CANCELED"

    status = models.CharField(max_length=10,
    # payment type
    created_on = models.DateTimeField(auto_now_add=True)

In Payment model add a field name "payment_type" and use foreign key field like below:

payment_type = models.ForeignKey(PaymentType, related_name="payments", on_delete=models.SET_NULL)
|improve this answer|||||

You may use a many-to-one relationship using a ForeignKey field from Payment class to the PaymentType class.

This field on the Payment class:

payment_type = models.ForeignKey(PaymentType, null=False, blank=False, on_delete=models.CASCADE)

This will create a relationship from a Payment to a PaymentType.


|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.