Django bulk_create 检查多个字段的重复输入

Django bulk_create check for duplicate entry of multiple fields

我正在尝试使用 bulk_create 进行大型数据集插入,因为我无法使用 get_or_create() 因为 N^N 问题

这里是 table 我正在尝试创建我的条目:

class SeatType(models.Model):
    ... other fields


class UserSeat(models.Model):
    user = models.ForeignKey("backend.User", null=True, blank=True, related_name='user_seat', on_delete=models.CASCADE)
    seat_type = models.ForeignKey("backend.SeatType", null=True, blank=True, related_name='user_seat_type', on_delete=models.CASCADE)

这是我的实现:

users = User.objects.all()
user_seats = [
      UserSeat(
              user=user,
              seat_type=SeatType.objects.all()[random_entry]
      )
      for user in users
]
UserSeat.objects.bulk_create(user_seats, None, ignore_conflicts=True)

问题是我想检查具有 2 列(用户,seat_type)值的唯一重复条目

例如:

user       |seat_type  | ...
---------- | --------- | ...
1          |1          | ...
2          |2          | ...
3          |4          | ...
4          |1          | ...
1          |1          | ...
3          |4          | ...

(1, 1) and (3, 4) 插入时无效 但是 ignore_conflict 只触发 1 个唯一列(这不是我想要的,它是 2 列的唯一值),我正在寻找类似 get_or_createdefaults,我的数据库是MySQL.

列可以重复,但每一行必须是一对唯一的 userseat_type 数据

您应该添加 Unique constraint as ignore_conflicts is resolved on database level as documented

class UserSeat(models.Model):

    ...

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['user', 'seat_type'], 
            name='unique_user_seat')
        ]
   

只需要在 SeatType 模型中使用 ManyToManyField 并设置为 UserSeat 模型,无需再创建手册。

例如

class SeatType(models.Model):
    ... other fields
    users = models.ManyToManyField(User, through='UserSeat')

class UserSeat(models.Model):
    user = models.ForeignKey("backend.User", null=True, blank=True, related_name='user_seat', on_delete=models.CASCADE)
    seat_type = models.ForeignKey("backend.SeatType", null=True, blank=True, related_name='user_seat_type', on_delete=models.CASCADE)
    ...other fields (modified, created, ...)

更多信息:https://docs.djangoproject.com/en/3.1/topics/db/models/#extra-fields-on-many-to-many-relationships