在创建期间设置模型的父级

时间:2014-12-18 17:11:08

标签: python django

背景信息:

几周前我刚刚开始使用Web框架,我想我应该首先尝试使用RoR。当我遇到一些与RoR有关的时候,我想我会尝试其他几个,这些都指导我走向Django。我已经成为狂热的Ruby和Python用户已有几年了,这个网站帮助我解决了很多问题。我正在尝试使用产品模型和位置模型为库存房间设置产品数据库。库存室由架子架组成,架子上有货架,里面装有箱子。使用这个,我使用isle,rack(称为segment),shelf和box组合了一个临时坐标系。例如,“G1C4”的位置将位于isle G,机架1,机架C和框4上。在RoR中,我能够使用位置名称,产品名称,数量和MPN(制造商)创建Product对象零件号)。创建产品后,将使用Regex将产品添加到相应的位置。

问题:

修改

在保存产品之前,如何重载模型的方法以使用匹配的位置自动填充位置字段?

当前代码:

产品型号:

class Product(models.Model):

    location_name = models.CharField(max_length=12)
    product_name = models.CharField(max_length=200)
    quantity = models.IntegerField(default=1)
    mpn = models.CharField(max_length=200)

    location = models.ForeignKey(Location)

位置模型:

class Location(models.Model):

    isle = models.CharField(max_length=3)
    segment = models.CharField(max_length=3)
    shelf = models.CharField(max_length=3)
    box = models.CharField(max_length=3)

相当于RoR:

class Product < ActiveRecord::Base
belongs_to :location, inverse_of: :products, foreign_key: "location_id"

before_validation do
    create_parent()
end

def create_parent()
    attrs = new_loc() # method that used Regex to find the coordinates

    Location.where(location_name: self.location_name).first_or_initialize do |loc|
        loc.isle_id = attrs['isle']
        loc.segment_id = attrs['segment']
        loc.shelf_id = attrs['shelf']
        loc.box_id = attrs['box']
        loc.item_list = []
        loc.save!
    end

    loc = Location.where(location_name: self.location_name).take!
    loc.item_list << self.mpn
    loc.save!

    self.location_id = loc.id

end

修改 我正在审查我的帖子,我意识到标题与这个问题并不完全相关。

1 个答案:

答案 0 :(得分:0)

这很简单,你只需创建一个位置

l = Location(...)
l.save()

以及具有该位置的产品

p = Product(location=l, ...)
p.save()

p = Product(...)
p.location = l
p.save()

修改

假设product.location会包含类似&#34; G1C4&#34;在创建时(例如,您使用p = Product(location_name="G1C4", product_name="cisco 123", quantity=3, mpn="something")之类的内容创建产品),您可以覆盖Product的保存方法,以自动创建或设置该产品的相应位置

class Product(models.Model):

    location_name = models.CharField(max_length=12)
    product_name = models.CharField(max_length=200)
    quantity = models.IntegerField(default=1)
    mpn = models.CharField(max_length=200)

    location = models.ForeignKey(Location)

    def save(self, *args, **kwargs):
        isle = self.location_name[0]
        segment = self.location_name[1]
        shelf = self.location_name[2]
        box = self.location_name[3]
        self.location = Location.objects.get_or_create(
                            isle=isle,
                            segment=segment,
                            shelf=shelf,
                            box=box)
        super(Product, self).save(*args, **kwargs)

因此,当您致电p.save()时,会为地理位置属性设置匹配的位置,如果该位置尚未存在,则会自动创建。