问题描述
我找不到关于这种关系的任何信息(一切都是关于一对一,一对多或多对多的)。甚至那些看起来也太复杂了,无法满足我的需求。
我有一个包含任务的表格和一个包含图像的表格。多个任务可以具有相同的映像以节省空间(删除任务时不会删除该映像)。我有一个执行任务的实体
import android.graphics.Bitmap
import androidx.room.*
@Entity(tableName = "tasks")
class Task(
@PrimaryKey(autoGenerate = true)
val id: Long,val imageId: Long = 0,// this needs a foreign key to Image
val image: Image
)
和另一个用于图像
import androidx.room.ColumnInfo
import androidx.room.PrimaryKey
@Entity(tableName = "images")
class Image (
@PrimaryKey(autoGenerate = true)
val id: Long,val title: String,@ColumnInfo(typeAffinity = ColumnInfo.BLOB)
val data: ByteArray? = null
)
如何为foreignKey
列添加imageId
,使其指向Image
?我是否可以直接获取一个Image
对象作为Task
的成员而不必创建另一个类?
解决方法
您必须在此处使用一对多关系。 d.android.com有example。如果愿意,您将拥有一个Task实体,一个Image实体和一个数据类TaskWithImage,就像在提供的示例中一样。
,class HomeView(ListView,LoginRequiredMixin):
model = Post
template_name = "home.html"
def __init__(self,*args,**kwargs):
print(self.request.user,self.request.user.username) # print user & username
return super().__init__(*args,**kwargs)