Django使用SmallUUIDField()id创建一个genericForeignKey

时间:2018-10-17 20:34:12

标签: python django generic-foreign-key

这是我的模型,该模型使用通用外键im对pos_idobject_id使用SmallUUIDField。

class POSRecord(models.Model):
    id = SmallUUIDField(default=uuid_default(), primary_key=True, db_index=True, editable=False, verbose_name='ID')

    # FK to a POS integration (e.g., SquareCredentials)
    pos_content_type = models.ForeignKey('contenttypes.ContentType',
        related_name='pos_record_integration',
        on_delete=models.CASCADE)
    pos_id = SmallUUIDField()
    pos = GenericForeignKey('pos_content_type', 'pos_id')

    # FK to anything in our system (e.g., Item, ModifierList, Location)
    object_content_type = models.ForeignKey('contenttypes.ContentType',
        related_name='pos_record_object',
        on_delete=models.CASCADE)
    object_id = SmallUUIDField()
    object = GenericForeignKey('object_content_type', 'object_id')

    # Raw JSON data from the POS api
    data = JSONField()

POSRecord.objects.get_or_create(方法上,将我从squareup的api获取的ID传递给键object_id,并获得E ValueError: bytes is not a 16-char string。我尝试将POSRecord模型pos_id的值更改为models.PositiveIntegerField(),但出现此错误。 ValueError: invalid literal for int() with base 10: 4JSZ539TSJ5GEIMW43FFNQXF

    def sync_item(self, square_item):
        item_content_type = ContentType.objects.get_for_model(Item)
        square_credential_content_type = ContentType.objects.get_for_model(SquareCredential)
        print(square_item.id)
        print(self.credentials.token)
        # Fetch our opy of the POS data
        try:
            record = POSRecord.objects.get_or_create(
                pos_content_type=square_credential_content_type,
                pos_id=self.credentials.token,
                object_content_type=item_content_type,
                object_id=square_item.id,
            )
        except POSRecord.DoesNotExist:
            record = POSRecord(pos=self.credentials)

        # Update our record with the fresh data
        record.data = square_item
        print(record)
        print(record.objects)
        # Get or instantiate our own version of the object 
        item = record.object
        if item is None:
            item = Item(tenant=self.tenant)
        print(item)
        # Update our version with the POS data
        item.name = record.data['name']
        item.decription = record.data['decription']

        # Save the world.
        item.save()
        if not record.object:
            record.object = item
        record.save()

0 个答案:

没有答案