I have following code
class Version(models.Model):
version = CharFeild
version_url = UrlField
class MyModel(models.Model):
name = CharFeild
default_version = OnetoOneField(Version)
available_versions = ForeignKeyField(Version)
i am getting stuck at when selecting available version i am only able to pick one, where i want to select all available or all the ones i require.
CodePudding user response:
You can use ForeignKey.related_name, as Django documentation says will help you
you can use it like this
class Version(models.Model):
version = CharFeild
version_url = UrlField
class MyModel(models.Model):
name = CharFeild
default_version = OnetoOneField(Version)
available_versions = ForeignKeyField(Version, related_name='model')
And you can use it like that
version = Version.objects.get(version="1.1.0")
models = version.model.all()
Also check this question and this question
CodePudding user response:
ForeignKeyField
refers to one Version
from MyModel
You are misunderstanding the purpose of foreign keys. Your MyModel
needs to be parent to all Version
, that are used as available_versions
, so that means You have to have one parent from child model, so your parent will have multiple childs and children will have only one parent. That means you have to use ForeignKeyField
inside Versions
class Version(models.Model):
version = CharFeild
version_url = UrlField
model = ForeignKey('MyModel', on_delete=models.CASCADE, related_name='available_versions', null=True, blank=True)
class MyModel(models.Model):
name = CharFeild
default_version = OnetoOneField(Version, related_name='default_model')
I am not sure that there won't be any related_names
collision (as it's a bit quirky), but I think you get the point