Django

时间:2018-04-25 02:25:36

标签: django many-to-many models

我有两个类,它们之间有两对多关系。由于相邻表还必须具有其他属性,因此我明确定义了它们。但我收到一条错误,说我需要更改相关名称。不知道该怎么做。非常感谢任何帮助。

这是我的models.py代码:

class Client(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    password = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = UserManager()

    def __repr__(self):
        return "<User object: {} {} {} {}>".format(self.first_name, 
self.last_name, self.email, self.password)

class Therapist(models.Model):
    name = models.CharField(max_length=255)
    reviews = models.ManyToManyField(Client, through="Review")
    appts = models.ManyToManyField(Client, through="Appointment")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = UserManager()

    def __repr__(self):
        return "<Book object: {}>".format(self.title)



class Review(models.Model):
    reviewer = models.ForeignKey(Client, on_delete=models.CASCADE)
    therapist_reviewed = models.ForeignKey(Therapist, 
on_delete=models.CASCADE)
    rating = models.IntegerField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    content = models.TextField()

    def __repr__(self):
        return "<Review object: {} {}>".format(self.book_reviewed, 
self.reviewer)

class Appointment(models.Model):
    booked_therapist = models.ForeignKey(Therapist, 
on_delete=models.CASCADE)
    booked_client = models.ForeignKey(Client, on_delete=models.CASCADE)
    date = models.DateTimeField()
    massage = models.CharField(max_length=255)

1 个答案:

答案 0 :(得分:2)

class Therapist(models.Model):
    name = models.CharField(max_length=255)
    reviews = models.ManyToManyField(Client, related_name='therapist_reviews', through="Review")
    appts = models.ManyToManyField(Client, related_name='therapist_appts', through="Appointment")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = UserManager()

    def __repr__(self):
        return "<Book object: {}>".format(self.title)

如果您没有为many_to_many字段分配related_name,则默认相关将设置为model_lower_case_set,但是当您有两个与同一模型相关的many_to_many字段时,默认相关名称为两个filed与model_lower_case_set相同,当使用related_name查询查询集时,这将导致冲突。