0

I'm kind of new to django. While writing the models for an app I'm doing, I felt like I was doing something wrong because of all the foreign keys I was using for a single model (ticket model to be specific)

My thinking at the beginning was that I wanted each Ticket to keep the information on it's creator, what team this ticket is assigned to and the comments made on the ticket. And other information that don't need foreign keys. Am I doing this right ? I dont know why, but I feel like there is a better way.

class Team(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=2000)
    members = models.ManyToManyField(User, through='Team_members')

    def __str__(self):
        return self.name



class Ticket(models.Model):
    name = models.CharField(max_length=200)
    creator = models.ForeignKey(User, on_delete=models.CASCADE)
    team = models.ForeignKey(Team, on_delete=models.CASCADE)
    comments = models.ForeignKey(Comment, on_delete=models.CASCADE)
    #worker = models.ForeignKey(User, on_delete=models.CASCADE) *to be finished
    description = models.CharField(max_length=500)
    status = models.BooleanField(default=False)
    date_opened = models.DateTimeField('date opened')
    date_closed = models.DateTimeField('date closed',null=True, blank=True)
    def __str__(self):
        return self.name



class Team_member:
    team = models.ForeignKey(Team)
    user = models.ForeignKey(User)
    date = models.DateTimeField('date joined')

class Comment:
    text = models.CharField(max_length=2000)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    def __str__(self):
        return self.text
siggibk
  • 11
  • 2
  • Also, just a hint, [auto_now_add](https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.DateField) will help you with `DateField`/`DateTimeField` on `Team_member` and `date_opened` on `Ticket`. – Art Oct 20 '17 at 05:04
  • Just a Django hint: See if GenericRelations will help your system. You may benefit from replacing the `Ticket.comments` FK with a GR. https://simpleisbetterthancomplex.com/tutorial/2016/10/13/how-to-use-generic-relations.html – White Oct 20 '17 at 06:22

1 Answers1

1

Your question actually has very little (like, nothing?) to do with Django. Please read about database normalization, it should answer your questions.

Regarding your models, I could notice the following:

  • Your models look quite good. Don't be afraid of foreign keys, they are the main reason you use a relational database :)
  • I assume, User might be a member of a Team (service?) or somebody who opens a ticket. If so: when you will have worker foreign key, you most likely won't need team in the Ticket model. It will be redundant, as worker would have a relation to Team.
  • Nitpicking: Team_member is not pythonic, a PEP8 compliant version would be TeamMember
Art
  • 2,235
  • 18
  • 34