简体   繁体   中英

Natural-key serialize Django model with one-to-one field as primary key

I have a Recipe model and Label model referring to the former with a OneToOneField . I put managers and natural_key methods to export both models with JSON encoding.

class RecipeManager(models.Manager):
    def get_by_natural_key(self, name):
        return self.get(name=name)

class Recipe(models.Model):
    objects = RecipeManager()

    name = models.CharField(max_length=255)

    def natural_key(self):
        return (self.name)


class LabelManager(models.Manager):
    def get_by_natural_key(self, recipe):
        return self.get(recipe=recipe)

class Label(models.Model):

    objects = LabelManager()

    recipe = models.OneToOneField(Recipe, primary_key=True)
    name = models.CharField(max_length=255)

    def natural_key(self):
        return self.recipe.natural_key()
    natural_key.dependencies = ['labels.recipe']

I export the Label queryset using natural keys:

with open(l_filename, 'w') as l_file:
    serialize('json',
              Label.objects.all(),
              indent=2,
              use_natural_foreign_keys=True,
              use_natural_primary_keys=True,
              stream=l_file)

Everything works fine but the serialized JSON objects have no field to Recipe model they should refer to.

[{"fields": {"name": null},"model": "labels.label"}]

Django docs, as of 1.7, doesn't give any hint specific to one-to-one relations with natural keys. Any advise?

name field in recipe model is not unique.

natural key must be unique to identify the object.When we define natural keys django creates index on the single unique field or on multiple fields unique together.

Note:

Whatever fields you use for a natural key must be able to uniquely identify an object. This will usually mean that your model will have a uniqueness clause (either unique=True on a single field, or unique_together over multiple fields) for the field or fields in your natural key. However, uniqueness doesn't need to be enforced at the database level. If you are certain that a set of fields will be effectively unique, you can still use those fields as a natural key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM