Ginger Bread
Ginger Bread

Reputation: 625

Django models relationships

I build an application where people post ads for sale different things like a cars,apartments, gadgets & etc. I have models with its own special fields for each item like a : CarModel, ApartmentModel, SmartphoneModel etc...

And I have a model Article : and want to add field item_of_sale which can be instance of different models (for example CarModel or ApartmentModel).

class Article(models.Model):

author = 
    models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles' )
    category = models.ForeignKey(Category,on_delete=models.CASCADE )        
    title = models.CharField(max_length=120)
    text = models.TextField()

    item_of_sale = # ??????? models.OneToOneField I suppose

I try something like this:

class CarModel(models.Model):
   ad = models.OneToOneField(Article, on_delete=models.CASCADE, 
                             related_name='item_of_sale')
   marc = models.CharField(max_length=40, choices=MARC_CHOICES)
   model = models.CharField(max_length=120, default='')
   .....


class ApartmentModel(models.Model):
   ad = models.OneToOneField(Article, on_delete=models.CASCADE, 
                             related_name='item_of_sale')
   location= models.CharField(max_length=200 )
   address= models.CharField(max_length=120)
   .....

But django does not allow to have more than one model with related_name="item_of_sale" .

Have you any ideas how I can make database with this kind of relations. Please any help . Thank you in advance.

Upvotes: 1

Views: 85

Answers (1)

biswa1991
biswa1991

Reputation: 546

related name is for backward query .relented name is optional field related need to be unique . your model is very simple you don't need any related name.`define you model with out related name . .

Upvotes: 1

Related Questions