对于以下API端点,
import json
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponseBadRequest
from django.views.decorators.http import require_POST
from lucy_web.models import UserApn
@login_required
@require_POST
def save_apn(request, version):
player_id = json.loads(request.body).get('player_id')
if player_id:
UserApn.objects.get_or_create(user=request.user, player_id=player_id)
return JsonResponse({'status': 'success'})
else:
return HttpResponseBadRequest()
这是基础模型:
from django.contrib.auth.models import User
from django.db import models
from .timestamped_model import TimeStampedModel
class UserApn(TimeStampedModel):
user = models.ForeignKey(User)
player_id = models.CharField(max_length=255)
对get_or_create()
的调用已引发一些MultipleObjectsReturned
错误。为了解决这个问题,我想对unique_together
和user
施加player_id
约束。但是,首先,我必须编写数据迁移,以消除违反此唯一共同约束的行。
如何编写一个选择这些查询的查询?现在提出了以下建议:
def remove_duplicate_apns(apps, schema_editor):
UserApn = apps.get_model('lucy_web', 'UserApn')
previous_user_id = None
previous_player_id = None
for apn in UserApn.objects.all().order_by('user_id', 'player_id'):
if apn.user_id == previous_user_id and apn.player_id == previous_player_id:
print(f'deleting {apn} (id: {apn.id})')
apn.delete()
else:
previous_user_id = apn.user_id
previous_player_id = apn.player_id
不过,这似乎也可以在单个查询中完成。
更新
我发现一个人可以将user
和player_id
这两个字段传递给.values()
,然后使用.distinct()
检查重复项。例如,以下测试通过:
from django.test import TestCase
from django.contrib.auth.models import User
from myapp.models import UserApn
class UserApnTest(TestCase):
def test_1(self):
user = User.objects.create_user(username='jayz')
apn1 = UserApn.objects.create(user=user, player_id='foo')
apn2 = UserApn.objects.create(user=user, player_id='foo')
apn3 = UserApn.objects.create(user=user, player_id='bar')
self.assertEqual(
len(UserApn.objects.values('user', 'player_id')) -
len(UserApn.objects.values('user', 'player_id').distinct()), 1)
问题仍然存在,那就是此输出是带有user_id
和player_id
的字典,但是原始的id
丢失了,所以我以后不能{{1} }复制对象并删除它们。我该如何做类似的事情,但保留对重复对象的引用?
答案 0 :(得分:1)
我设法将重复的UserApn
分为以下查询集:
UserApn.objects.all().difference(UserApn.objects.distinct('user', 'player_id'))
请注意,将多个参数传递给distinct()
仅适用于PostgreSQL。