Bạn có thể sử dụng thuộc tính _meta
của mô hình để lấy đối tượng trường và từ trường, bạn có thể nhận được mối quan hệ và nhiều hơn nữa, ví dụ: xem xét một bảng nhân viên trong đó có một khóa ngoại đến một bảng phận
In [1]: from django.db import models
In [2]: model = models.get_model('timeapp', 'Employee')
In [3]: dep_field = model._meta.get_field_by_name('department')
In [4]: dep_field[0].rel.field_name
Out[4]: 'id'
In [5]: dep_field[0].rel.to
Out[5]: <class 'timesite.timeapp.models.Department'>
từ django/db/mô hình/options.py
def get_field_by_name(self, name):
"""
Returns the (field_object, model, direct, m2m), where field_object is
the Field instance for the given name, model is the model containing
this field (None for local fields), direct is True if the field exists
on this model, and m2m is True for many-to-many relations. When
'direct' is False, 'field_object' is the corresponding RelatedObject
for this field (since the field doesn't have an instance associated
with it).
Uses a cache internally, so after the first access, this is very fast.
"""
Nguồn
2010-03-05 06:10:31
Câu hỏi hay. Điều này đã lưu ass của tôi – GabiMe