gpt4 book ai didi

python - 如何根据其他实体的数据通过tastypie选择在django中创建或不创建实体?

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:23 25 4
gpt4 key购买 nike

我有一个事件类,其中定义了参与者数量和参与者限制,以及代表事件注册的票证类。

我希望当关联的事件已满时 (maxPersons==registredPersons),不会创建一个事件的门票。

事件和门票将通过 Android 的 tastypie RESTapi 上传。

请问有什么更简单的方法吗?

所以我有这个类代表一个事件:

class Event(models.Model):
user = models.ForeignKey(User, unique=False)
maxPersons = models.IntegerField()
registredPersons = models.IntegerField()

这个类是事件的注册:

class Ticket(models.Model):
event = models.ForeignKey(Event, unique=False)
user = models.ForeignKey(User, unique=False)

这是事件的 tastypie 资源类:

class EventResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = Event.objects.all()
resource_name = 'events'
include_resource_uri = False
authorization= Authorization()
authentication = BasicAuthentication()



def alter_list_data_to_serialize(self, request, data_dict):
if isinstance(data_dict, dict):
if 'meta' in data_dict:
#Get rid of the meta object
del(data_dict['meta'])

return data_dict

这个是票务:

class TicketResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
event = fields.ForeignKey(EventResource,'journey')
class Meta:
queryset = Ticket.objects.all()
resource_name = 'tickets'
include_resource_uri = False
authorization= Authorization()
authentication = BasicAuthentication()
filtering = {
'user': ALL_WITH_RELATIONS,
}
def get_object_list(self, request):
return super(TicketResource, self).get_object_list(request).filter(user = request.user)


def alter_list_data_to_serialize(self, request, data_dict):
if isinstance(data_dict, dict):
if 'meta' in data_dict:
#Get rid of the meta object
del(data_dict['meta'])


return data_dict

最佳答案

如果事件已满,仅覆盖授权将不允许用户创建门票。

class TicketAuthorization(Authorization):
def create_detail(self, object_list, bundle):
return bundle.obj.event.registredPersons <= bundle.obj.event.maxPersons:

class TicketResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
event = fields.ForeignKey(EventResource,'journey')
class Meta:
queryset = Ticket.objects.all()
resource_name = 'tickets'
include_resource_uri = False
authorization= TicketAuthorization()
authentication = BasicAuthentication()
filtering = {
'user': ALL_WITH_RELATIONS,
}

[...]

关于python - 如何根据其他实体的数据通过tastypie选择在django中创建或不创建实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23662342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com