0

i want to set relation in that case

class SaleType(models.Model):
    price = models.CharField(max_length=50)
    contract = models.CharField(max_length=50)

    def __str__(self):
        return str(self.price)

class SaleType2(models.Model):
    totalContract = models.CharField(max_length=50)
    requierd = models.CharField(max_length=50)

    def __str__(self):
        return str(self.totalContract)

class ForSale(models.Model):
    method = models.ForeignKey(Method, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.method)

if method in ForSale = Cash get foreign key for SaleType

if method in ForSale = Rent get foreign key for SaleType2

1 Answers1

0

I think GenericForeignKey is what you are looking for. More details here.

class ForSale(models.Model):
    method = models.CharField(choices=(('Cash', 'cash'), ('Rent', 'rent')), ...)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    ...

Add validations to support content_type limited to SaleType & SaleType2. Also maintain the relation in each row between method and content_type.

dxillar
  • 307
  • 2
  • 9
  • may be [this](https://stackoverflow.com/questions/13907211/genericforeignkey-and-admin-in-django) might help – dxillar Apr 09 '20 at 16:31