【问题标题】:Clashing reverse accessors and queries in Django for many to many field?在 Django 中为多对多字段冲突反向访问器和查询?
【发布时间】:2023-03-31 22:50:01
【问题描述】:
from django.db import models


class Appointment(models.Model):
    doctors = models.ManyToManyField('Doctor', through='AppointmentAccess', related_name='appointments')


class Doctor(models.Model):
    appointments = models.ManyToManyField('Appointment', through='AppointmentAccess', related_name='doctors')

我收到以下错误:

core.Appointments.doctors: (fields.E302) Reverse accessor for 'PatientProfile.users' clashes with field name 'Doctor.appointments'.
        HINT: Rename field 'Doctor.appointments', or add/change a related_name argument to the definition for field 'Appointment.doctors'.
core.Appointment.doctors: (fields.E303) Reverse query name for 'Doctor.appointments' clashes with field name 'Appointment.doctors'.
        HINT: Rename field 'Doctor.appointments', or add/change a related_name argument to the definition for field 'Appointment.doctors'.
core.Doctor.appointments: (fields.E302) Reverse accessor for 'Doctor.appointments' clashes with field name 'Appointments.doctors'.
        HINT: Rename field 'Appointment.doctors', or add/change a related_name argument to the definition for field 'Doctor.appointments'.
core.User.patient_profiles: (fields.E303) Reverse query name for 'Doctor.appointments' clashes with field name 'Appointments.doctors'.
        HINT: Rename field 'Appointments.doctors', or add/change a related_name argument to the definition for field 'Doctor.appointments'.

为什么?有人可以帮我理解这个错误吗?应该通过 AppointmentAccess 表跟踪多对多字段,而不是生成新的中间表。相关姓名预约与医生有何冲突?

【问题讨论】:

  • 为什么两个模型都需要指定m2m?只需在其中一个中指定即可。

标签: python django database django-models orm


【解决方案1】:

您在两个模型中都指定了多对多关系。这不是必需的,因为 Django 会自动向关系中的其他模型添加反向关系,因此您可以简单地编写:

class Appointment(models.Model):
    # Remove below line
    doctors = models.ManyToManyField('Doctor', through='AppointmentAccess', related_name='appointments')
    ...


class Doctor(models.Model):
    appointments = models.ManyToManyField('Appointment', through='AppointmentAccess', related_name='doctors')

现在既然你已经设置了related_name(如果你没有默认设置为doctor_set,即小写的型号名称)如果你有一个Appointment的实例appointment你可以简单地写:

for doctor in appointment.doctors.all():
    print(doctor)

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 2014-04-27
    • 2021-08-13
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 2020-07-23
    • 1970-01-01
    相关资源
    最近更新 更多