当我创建一个像这样的对象时:
bus_stop_1 = 4(外键)
bus_stop_2 = 7
然后它应该自动创建其他对象
bus_stop_1 = 7
巴士站_2 = 4
** 时间和距离是相同的 ** BusStop 是一个模型 我的模特
class ConnectedRoute(models.Model):
bus_stop_1 = models.ForeignKey(
BusStop, on_delete=models.CASCADE, related_name='stop1')
bus_stop_2 = models.ForeignKey(
BusStop, on_delete=models.CASCADE, related_name='stop2')
distance = models.FloatField(blank=True, null=True)
time = models.TimeField(blank=True, null=True)
我已经尝试使用保存方法并保存 ConnectedRoute,但它被一次又一次地递归调用。
def save(self, *args, **kwargs):
# Check if the object is being created for the first time
if not self.pk:
# Create a new ConnectedRoute object with reversed bus stops
reverse_connected_route = ConnectedRoute(
bus_stop_1=self.bus_stop_2,
bus_stop_2=self.bus_stop_1,
distance=self.distance,
time=self.time
)
reverse_connected_route.save() # Save the reversed object
super().save(*args, **kwargs)
您应该使用
.get_or_create
- 仅当新实例不存在时才会创建新实例,如下所示:
reverse_connected_route, created = ConnectedRoute.objects.get_or_create(
bus_stop_1=self.bus_stop_2,
bus_stop_2=self.bus_stop_1,
)
if (reverse_connected_route.distance, reverse_connected_route.time) != (self.distance, self.time):
reverse_connected_route.distance = self.distance
reverse_connected_route.time = self.time
reverse_connected_route.save(update_fields=['distance', 'time'])
这个if语句将阻止递归调用 也许你需要移动
super().save()
到顶部
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=ConnectedRoute)
def trigger_reverse_route_creation(sender, instance, **kwargs):
if kwargs['created'] == True:
sender.objects.get_or_create(
bus_stop_1=instance.bus_stop_2,
bus_stop_2=instance.bus_stop_1,
defaults={'distance': instance.distance, 'time': instance.time}
)
但是如果更新了第一个路线的距离和时间,这种方法不会更新第二个路线的距离和时间。您必须在此处添加类似的
if
语句才能更新它。