简体   繁体   中英

How do can I creating and use a custom fields in Django

I am new to django and building a kinda of a package (Shipments) based app in Django and I have these models,

class ShippingLocation(models.Model):
    latitude = models.IntegerField()
    longitude = models.IntegerField()

class Shipping (models.Model):
    email = models.EmailField()
    location = models.ForeignKey(ShippingLocation , default=None, on_delete=models.CASCADE )

class Package(models.Model):
    name = models.CharField(max_length=30)
    supplier = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING)
    to =  models.ForeignKey(Shipping, default=None, on_delete=models.CASCADE )

this work okay for now but I wonder if can be able to remove the ShippingLocation model and use a custom field instead of at the location field in the Shipping model? If yes how do I create custom fields and how do I implement them?

so I have something like

class Shipping (models.Model):
    email = models.EmailField()
    location = models.DictionaryField()

and I get rid of the ShippingLocationModel

I guess you wanted to migrate your existing data from ShippingLocation into Shipping. If you are just on dev, simply delete your sqlite3 file and change to your models to your expectation.

If you are already on prod, I usually do this:

  1. Add a location_dictionary field in Shipping (not required). Migrate
  2. Write a one-time migration logic to move everything in ShippingLocation into location_dictionary field
  3. Remove the ShippingLocation model
  4. Remove the location field
  5. Rename the location_dictionary field...

This should be work:

  1. delete the SQLite database
  2. change the model
  3. then run the migrate command

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