0

I have two class model like this:

class Problem(models.Model):
    owner = models.ForeignKey(User)
    services = models.CommaSeparatedIntegerField(max_length=200)

class Services(models.Model):
    name = models.CharField(max_length=50)
    ...

As you see in Problem model I keep id's of Services in comma separated field. For example to solve this problem we should do this Services: "1,2,3". I want to show detail of problem and related services to user. To do this I should join Problem to Services table but I don't know how. Consider that I have limited number of Services that defined by super admin. for example I have 150 services.

Saber Solooki
  • 1,182
  • 1
  • 15
  • 34

2 Answers2

0

Use Services that contains a ForeignKey. Thus you can relate all service to one problem

Bobby
  • 1,511
  • 1
  • 15
  • 24
  • I have limited number of services that defined by super admin. for example 150 services. in Problem table I use this services to know witch service should be done to solve the problem – Saber Solooki Jan 20 '17 at 11:59
  • @user2141833 what do you mean. You still can access all the Services that are related to the problem by using `choice_set.all` – Bobby Jan 20 '17 at 12:01
  • @having a separted integer field is definitely not "The django way". You can have any information you want using a foreign key – Bobby Jan 20 '17 at 12:02
  • Any service have their field, for example have price , unit and etc. I may have many problem to use this services. So I can't use foreign key of problem in my services table – Saber Solooki Jan 20 '17 at 12:09
0

Use a ManyToManyField, this is exactly what they are used for.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
  • I don't want to use ManyToManyField because when I can use comma separated field to hold services why I use another table? – Saber Solooki Jan 20 '17 at 12:05
  • Duh -- so that you can use it for joins, select_related, and so on. If you want Django and the database to do your work for you, you'll have to tell them that something is a many to many relation. And why is a 200-max-length char field that has to be interpreted as comma seperated integers any better than another table? – RemcoGerlich Jan 20 '17 at 12:09
  • So we haven't comma separated with relation field in django? So you suggest I use another table in this situation? – Saber Solooki Jan 20 '17 at 12:14
  • Exactly, comma separated relations don't exist in relational databases, so not in Django either. Use a ManyToManyField (which will create another table in the background, but you usually will never notice). – RemcoGerlich Jan 20 '17 at 12:16
  • If I use another table , for one problem, for example, I have 3 raw that have id of problem and id of service. I feel this is not good structure – Saber Solooki Jan 20 '17 at 12:17