如何在创建对象时自动创建Django关系?

时间:2012-09-25 22:58:39

标签: django django-models django-admin

我希望用户能够创建Store对象。创建后,它应自动为此用户/商店组合创建EmploymentRelationship类型Owner。稍后,商店的Owner可以添加Employee。如何在管理界面中创建对象时如何建立此初始关系?

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)

1 个答案:

答案 0 :(得分: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