我正在使用Django REST Framework来存储来自扫描程序的数据,扫描程序是在检测到新扫描时向框架发送JSON POST请求的设备。模型如下:
class Location(models.Model):
address = models.CharField(max_length=300)
city = models.CharField(max_length=50)
state = models.CharField(max_length=100)
zipcode = models.IntegerField(null=True, blank=True)
latitude = models.FloatField(null=True, blank=True)
longitude = models.FloatField()
def __str__(self):
return self.address
class Scanner(models.Model):
location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True,related_name='scanner')
description = models.CharField(max_length=300, null=True, blank=True)
def __str__(self):
return self.location.address + ": " + self.description + " (id=" + str(self.pk) + ")"
class Scan(models.Model):
scanner = models.ForeignKey(Scanner, on_delete=models.CASCADE, null=True, blank=True,related_name='scan')
datetime = models.DateTimeField(null=True, blank=True, default=timezone.now())
def __str__(self):
if self.scanner != None:
return self.scanner.description + ": " + str(self.datetime)
else:
return "None: " + str(self.datetime)
class Meta:
ordering = ('datetime',)
序列化器就是这些:
class ScanSerializer(serializers.ModelSerializer):
class Meta:
model = Scan
fields = ('id', 'scanner', 'datetime')
class ScannerSerializer(serializers.ModelSerializer):
class Meta:
model = Scanner
fields = ('id', 'location', 'description',)
class UserSerializer(serializers.ModelSerializer):
scans = serializers.PrimaryKeyRelatedField(many=True, queryset=Scan.objects.all())
class Meta:
model = User
fields = ('id', 'username', 'scans')
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = ('id', 'address', 'city', 'state','zipcode', 'latitude', 'longitude')
如果我使用DRF URL创建新的Scan和Scanner对象,它可以正常工作。但是,当我发送这样的JSON请求时:
data={"location": "2", "description": "Test scanner"}
无法创建新对象。我认为这个问题只是指他们的ID。但是,当我尝试在框架中创建嵌套对象并发送包含嵌套对象的JSON请求时,它会抛出一个AssertionError,表示我没有正确填充所有字段。如何格式化JSON请求以创建具有与现有对象的外键关系的对象?