我正在使用Django rest框架创建API。我有一张桌子,将用作产品的类型。另一个表,它将与产品映射该类型。将其视为producttypesmapping
表。因此,我正在创建产品类型更新终结点。只会更新producttypesmapping
。
问题是我在序列化程序中使用了ChoiceField()。因此,我需要元组tuples变量来防止存储不必要的值。它将在util.py中初始化并使其动态,可以通过查询producttypes
表直接加载。因此,我只需要查询一次数据。
TAG_CHOICES_TYPE_ONE = []
tags = ProductTypes.objects.filter(tag_type_id=1).values('id', 'value')
for index, item in enumerate(tags):
TAG_CHOICES_TYPE_ONE.append((item["id"], item["value"]))
TAG_CHOICES_TYPE_ONE = tuple(TAG_CHOICES_TYPE_ONE)
但是问题是在producttypes
甚至用任何数据初始化之前都执行过utils.py。
答案 0 :(得分:1)
首先,除非您希望附加一些有关映射的其他数据,否则不需要映射模型。只需使用import pygame, random
import sys
WHITE = (255, 255, 255)
GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
SCREENWIDTH=1000
SCREENHEIGHT=578
class Worker(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
def create_randomPATH(self,x,y):
randomX = random.randint(1,5)
randomY = random.randint(1,5)
if random.uniform(0,1)>0.5:
valX = x + randomX
valY = y + randomY
else:
valX = x - randomX
valY = y - randomY
return valX, valY
class Background(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
pygame.init()
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
screen_rect=screen.get_rect()
pygame.display.set_caption("TEST")
worker = Worker("worker.png", [0,0])
w_x = worker.rect.left
w_y = worker.rect.top
bg = Background("background.jpg", [0,0])
carryOn = True
clock=pygame.time.Clock()
while carryOn:
for event in pygame.event.get():
if event.type==pygame.QUIT:
carryOn=False
pygame.display.quit()
pygame.quit()
quit()
# Draw floor layout
screen.blit(pygame.transform.scale(bg.image, (SCREENWIDTH, SCREENHEIGHT)), bg.rect)
# Draw obstacles
pygame.draw.rect(screen, GREEN, [510,150,75,52])
pygame.draw.rect(screen, GREEN, [450,250,68,40])
w_x,w_y = worker.create_randomPATH(w_x,w_y)
# worker should not go outside the screen area
worker.rect.clamp_ip(screen_rect)
screen.blit(worker.image, (w_x,w_y))
# Refresh Screen
pygame.display.flip()
clock.tick(5)
pygame.display.quit()
pygame.quit()
quit()
或ForeignKey
。
然后,您应该考虑使用PrimaryKeyRelatedField
而不是ManyToManyField
。该字段以queryset作为参数,这将有助于您限制选择。如果您选择ChoiceField
以便能够在可浏览的API中很好地显示,则可以通过为模型创建string representation来实现相同的目的。