Home > Blockchain >  one-to-one relationship but of multiple types in Django
one-to-one relationship but of multiple types in Django

Time:08-19

I'm creating an online shop with Django. I figured since there could be different types of item for sale that share some attributes and fields, I'd better make an Item Model and other models subclass it. So I now have an abstract Item model and some other models like Dress, Pants and shoes. Now I wanna have a new model (e.g. Comment) which should have a relationship with the Item model. But since Item model is abstract I can't do it. Is there way I could have a one to one relationship whose one side could accept different types? Some thing like this:

class Comment(models.Model):

    item = models.ForeignKey(to=[Dress, Pants, Shoes])

CodePudding user response:

One Foreing key field can lead only to one instance, in a database it would look like this:

|id|  item |
|13|t-shirt|    

The best way to solve your problem is to use these three models:

class Item_type(models.Model):
    #here you should create as many instances as you have types of your items
    # one item_type = Dress, second = Pants, third = Shoes
    title = models.CharField(max_length=50)

class Item(models.Model):
    #here you create your item, with title for example Nike Brand new shooes
    title = models.CharField(max_length=150)
    #and choosing type in oneToOneField = shooes
    item_type = models.OneToOneField(Item_type, on_delete=models.CASCADE)


class Comment(models.Model):
    #here you have your comments for your Item
    item = models.ForeignKey(Item, on_delete=models.CASCADE)

CodePudding user response:

Generic Relations sounds like solution, in your Comment model add these fields:

class Comment(models.Model):
    [Other fields]
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()

and in your abstract Item model add GenericRelation field

class Item(models.Model):
    [Other fields]
    comments = GenericRelation(Comment)
    
    class Meta:
        abstract=True
  • Related