我有两个表用户和地址。用户有很多要求。
class User(models.Model):
user_id=models.AutoField(primary_key = True)
catcher_fname = models.CharField(max_length = 128, blank = True)
catcher_lname = models.CharField(max_length = 128, blank = True)
api_key = models.CharField(max_length = 100, blank = False)
class Address (models.Model):
address_id=models.AutoField(primary_key = True)
address = models.CharField(max_length = 150)
city = models.CharField(max_length = 255)
user = models.ForeignKey(User)
当我点击用户表时,我也想要他的地址并返回JSON。
user = User.obejcts.get(pk = 2)
它只返回用户数据而不是地址:(
答案 0 :(得分:2)
models.py -
class User(models.Model):
catcher_fname = models.CharField(max_length = 128, blank = True)
catcher_lname = models.CharField(max_length = 128, blank = True)
api_key = models.CharField(max_length = 100, blank = False)
class Address (models.Model):
address = models.CharField(max_length = 150)
city = models.CharField(max_length = 255)
user = models.ForeignKey(User,on_delete=models.CASCADE)
注意 - id字段是在django中自动增量和内置的,您无需直接指定。 以下是演示如何链接用户obj和地址obj。
>> from .models import User,Address
>> user_obj = User.objects.get(pk=pk)
>> address_obj = Address.objects.get(pk=address_pk)
>> user_obj.address = address_obj
>> user_obj.save()
稍后您可以从用户对象访问地址 -
>> from .models import User
>> user_obj = User.objects.get(pk=pk)
>> user_obj.address_set.all() (will give the data)