Django模型外键自动填充

时间:2015-09-02 06:57:35

标签: django django-models django-views

我有两个模型类用户和帐户一起链接或由另一个名为useraccounts的表连接。

我想要的是,当我向他们提交数据(用户和帐户)时,useraccounts表也会自动填充用户和帐户表的ID。

这是我的示例模型代码。 Error page

class Account(models.Model):
    # fields
    id = models.IntegerField(primary_key=True)
    t_stamp = models.DateField(default=datetime.datetime.now())
    acctno = models.TextField(null=False, unique =True)
    acctname = models.TextField(null=False)
    status = models.TextField(null=False, choices=STATUS)
    accttype =  models.TextField(null=False,choices=ACCT_TYPE)
    acctclass = models.TextField(null=False, choices=ACCT_CLASS)
    min_balance = models.FloatField(default=0)
    cur_balance = models.FloatField(default=0)
    ava_balance = models.FloatField(default=0) 
    #fundingsources = models.ManyToManyField(FundingSource)
    class Meta:
        managed = False
        db_table = 'accounts'

    def save(self, *args, **kwargs):
       super(Account, self).save(*args, **kwargs)
       try:
           self.useraccount_set.all()[0]
       except:
           UserAccount.objects.bulk_create([UserAccount(account_id=self,user_id=user) for user in User.objects.all()])

    class User(AbstractBaseUser, PermissionsMixin):
    id      = models.AutoField(primary_key=True)
    username = models.TextField(unique=True, null=True)
    fullname = models.TextField(null=False)
    country = models.TextField(null=True)
    email = models.EmailField( unique=True, db_index=True)
    phone = models.TextField()
    address = models.TextField()
    activation_key = models.CharField(max_length=40)
    key_expires = models.DateTimeField(null=True)
    date_joined = models.DateTimeField(default=timezone.now)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=True)
    #accounts = models.ManyToManyField(Account, through='UserAccount')


    class  Meta:
        db_table = "users"


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
    objects = UserManager()


    def get_short_name(self):
    return self.fullname


    def  get_username(self):
    return self.email

    def is_authenticated(self): 
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin    



signals.post_save.connect(create_auth_client, sender=User)
User._meta.get_field_by_name('email')[0]._unique=True 


    class UserAccount(models.Model):
    user_id = models.ForeignKey(User)
    account_id = models.ForeignKey(Account)

    class Meta:
        managed = False
        db_table = 'useraccounts'


class UserAccount(models.Model):
    user_id = models.ForeignKey(User)
    account_id = models.ForeignKey(Account)

class Meta:
    managed = False
    db_table = 'useraccounts'

1 个答案:

答案 0 :(得分:0)

您必须在模型保存方法中执行此操作:

class Account(models.Model):

   id = models.IntegerField(primary_key=True)

   def save(self, *args, **kwargs):
       super(Account, self).save(*args, **kwargs)
       try:
           self.useraccount_set.all()[0]
       except:
           UserAccount.objects.bulk_create([UserAccount(account_id=self,user_id=user) for user in User.objects.all()])




class User(AbstractBaseUser, PermissionsMixin):
   id  = models.AutoField(primary_key=True)
   def save(self, *args, **kwargs):
       super(User, self).save(*args, **kwargs)
       try:
           self.useraccount_set.all()[0]
       except:
           UserAccount.objects.bulk_create([UserAccount(user_id=self,account_id=account) for account in Account.objects.all()])