2012-09-25 202 views
0

我想要一個用戶能夠創建一個Store對象。創建後,它應自動爲此用戶/商店組合創建EmploymentRelationship類型爲Owner。稍後,商店的Owner能夠添加Employee。儘管在管理界面中創建對象時,如何創建這種初始關係?如何在創建對象時自動創建Django關係?

class Store(models.Model): 
    description = models.CharField('Description of Store',max_length=45, null=False, blank=False) 

class EmploymentRelationship(models.Model): 
    OWNERTYPECHOICES = (
     (constants.OWNER, 'Owner'), 
     (constants.EMPLOYEE, 'Employee'), 
    ) 

    sid = models.ForeignKey(Store, null=False, blank=False) 
    uid = models.ForeignKey(User, null=False, blank=False) 
    employment_type = models.IntegerField('Ownership Type',default=constants.EMPLOYEE, choices=OWNERTYPECHOICES) 

回答

0

您可以在管理類中重寫save_model:

class StoreAdmin(ModelAdmin): 

    def save_model(self, request, obj, form, change): 
     super(StoreAdmin, self).save_model(request, obj, form, change) 
     if not change: 
      EmploymentRelationship.objects.create(
       sid=obj, uid=request.user, employment_type=constants.OWNER) 

更多信息here