[Python] Changed the relationship of a Foreign Key | Django model

Discussão em 'Python' iniciado por Stack, Junho 3, 2025.

  1. Stack

    Stack Membro Participativo

    my buyer field from the Sell model had relationship with the Buyer model like this:

    class Buyer(models.Model):
    name = models.CharField(max_length=200, blank=True)
    description = models.CharField(max_length=200, blank=True)

    class Sell(models.Model):
    item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE)
    buyer = models.ForeignKey(**Buyer**, related_name='sell', on_delete=models.CASCADE)


    But now, it's set to 'User' model as you can see below:

    class Sell(models.Model):
    item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE)
    buyer = models.ForeignKey(**User**, related_name='sell', on_delete=models.CASCADE)


    When I go to Django admin, it shows me all the available users from the User model but if I try to save, I got an error like this:

    insert or update on table "dma_sell" violates foreign key constraint "dma_sell_buyer_id_4d165f92_fk_dma_buyer_id"
    DETAIL: Key (buyer_id)=(13) is not present in table "dma_buyer".


    I'm wondering I should NOT have changed this but what is the best way to correct that? I really need to relate the buyer field with User model!

    Thank you!

    Continue reading...

Compartilhe esta Página