django accessing onetoonefield

  • Last Update :
  • Techknowledgy :

I think you need to pass the user object and not a string.

client1 = User.objects.get(username = "client_1") # this is the user object
client_obj = Client.objects.get(user = client1) # pass object NOT STRING

you can also do this: (assuming the user's id is given)

client1 = Client_objects.get(user__id = 1) # pass the user 's id instead

Suggestion : 2

What follows are examples of operations that can be performed using the Python API facilities.,To define a one-to-one relationship, use OneToOneField.,Using Django Models and databases Examples of model relationship API usage One-to-one relationships ,Examples of model relationship API usage One-to-one relationships

from django.db
import models

class Place(models.Model):
   name = models.CharField(max_length = 50)
address = models.CharField(max_length = 80)

def __str__(self):
   return "%s the place" % self.name

class Restaurant(models.Model):
   place = models.OneToOneField(
      Place,
      on_delete = models.CASCADE,
      primary_key = True,
   )
serves_hot_dogs = models.BooleanField(
   default = False)
serves_pizza = models.BooleanField(
   default = False)

def __str__(self):
   return "%s the restaurant" % self.place.name

class Waiter(models.Model):
   restaurant = models.ForeignKey(Restaurant, on_delete = models.CASCADE)
name = models.CharField(max_length = 50)

def __str__(self):
   return "%s the waiter at %s" % (self.name, self.restaurant)
>>> p1 = Place(name = 'Demon Dogs', address = '944 W. Fullerton') >>>
   p1.save() >>>
   p2 = Place(name = 'Ace Hardware', address = '1013 N. Ashland') >>>
   p2.save()
>>> r = Restaurant(place = p1, serves_hot_dogs = True, serves_pizza = False) >>>
   r.save()
>>> r.place
<Place: Demon Dogs the place>
>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant>
>>> from django.core.exceptions
import ObjectDoesNotExist
   >>>
   try:
   >>>
   p2.restaurant >>>
   except ObjectDoesNotExist:
   >>>
   print("There is no restaurant here.")
There is no restaurant here.

Suggestion : 3

Django behaves differently with access to the OneToOneField depending on which side of the relation is used. Currently UndergroundBar.place will return None while Place.undergroundbar raises DoesNotExist. ,© 2005-2022 Django Software Foundation unless otherwise noted. Django is a registered trademark of the Django Software Foundation. , I thought I had looked over existing tickets but it seems I missed one. dupe of #10227 ,Django Software Foundation

class Place(models.Model):
   name = models.CharField(max_length = 50)

class UndergroundBar(models.Model):
   place = models.OneToOneField(Place, null = True)

Suggestion : 4

I think you need to pass the user object and not a string.,Django Models: Accessing Parent Object Attribute Within a Related Object Using OneToOneField,Django - Accessing attributes through a OneToOneField,Accessing the first object in list to have an optional property in a Django template

I think you need to pass the user object and not a string.

client1 = User.objects.get(username = "client_1") # this is the user object
client_obj = Client.objects.get(user = client1) # pass object NOT STRING

you can also do this: (assuming the user's id is given)

client1 = Client_objects.get(user__id = 1) # pass the user 's id instead

Suggestion : 5

A OneToOneField is used when you want to create a One-to-one relations. In this article, we will go over the usecase for such a field and how it should be implemented.,You generally won't use one-to-one relationships that often and I also won't really advise them, except for very specific cases, like this one:,Say you have a user model. In that model you also store details about their profile (bio, address, profile picture etc). When that table gets very big, a lot of columns could influence the speed of retrieving items from that table. In that case, it might be a good idea to split the user details from the profile details and create a separated table from that. Connecting the two through a OneToOneField would make sense here, since generally a user won't have two profiles or vice versa.,Another advantage of this approach is that you can generally cache the Profile table for a longer time. But, again, I generally wouldn't recommend this approach as it makes things a lot more complicated.

class User(AbstractBaseUser):
   profile = OneToOneField(Profile, on_delete = models.CASCADE)
# other fields you want to add beside the
default ones from AbstractBaseUser

class Profile(models.Model):
   bio = TextField()
# more profile fields
u = User.objects.get(id = 1)
print(u.profile.bio)

Suggestion : 6

django.db.models.ForeignKey() , django.db.models.AutoField() , django.db.models.DateTimeField() , django.db.models.IntegerField()

def test_lookup_allowed_onetoone(self):
   class Department(models.Model):
   code = models.CharField(max_length = 4, unique = True)

class Employee(models.Model):
   department = models.ForeignKey(Department, models.CASCADE, to_field = "code")

class EmployeeProfile(models.Model):
   employee = models.OneToOneField(Employee, models.CASCADE)

class EmployeeInfo(models.Model):
   employee = models.OneToOneField(Employee, models.CASCADE)
description = models.CharField(max_length = 100)

class EmployeeProfileAdmin(ModelAdmin):
   list_filter = [
      'employee__employeeinfo__description',
      'employee__department__code',
   ]

ma = EmployeeProfileAdmin(EmployeeProfile, self.site)
# Reverse OneToOneField
self.assertIs(ma.lookup_allowed('employee__employeeinfo__description', 'test_value'), True)
# OneToOneField and ForeignKey
self.assertIs(ma.lookup_allowed('employee__department__code', 'test_value'), True)
def test_parent_child_one_to_one_link(self):
   # Since the parent and child are linked by an automatically created
# OneToOneField, you can get from the parent to the child by using the
# child 's name.
self.assertEqual(
   Place.objects.get(name = "Demon Dogs").restaurant,
   Restaurant.objects.get(name = "Demon Dogs")
)
self.assertEqual(
   Place.objects.get(name = "Ristorante Miron").restaurant.italianrestaurant,
   ItalianRestaurant.objects.get(name = "Ristorante Miron")
)
self.assertEqual(
   Restaurant.objects.get(name = "Ristorante Miron").italianrestaurant,
   ItalianRestaurant.objects.get(name = "Ristorante Miron")
)
def convert(self, dj_field):
   result = []
if isinstance(dj_field, (ForeignKey, OneToOneField)):
   result.append(dj_field.column)
convert_from = dj_field.target_field
else:
   result.append(dj_field.name)
convert_from = dj_field
internal_type = convert_from.get_internal_type()
convert_to = self._types.get(internal_type)
if convert_to is not None:
   result.append(self._convert_type(convert_from, convert_to))
else:
   logger.info(
      'Not found corresponding '
      'SQLAlchemy type for "%s"(%r)',
      internal_type,
      dj_field
   )
return sa.column( * result)
def _register_model(admin, model):
   if not hasattr(admin, 'reversion_format'):
   admin.reversion_format = 'json'

if not is_registered(model):
   inline_fields = []
for inline in getattr(admin, 'inlines', []):
   inline_model = inline.model
if getattr(inline, 'generic_inline', False):
   ct_field = getattr(inline, 'ct_field', 'content_type')
ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id')
for field in model._meta.many_to_many:
   if isinstance(field, GenericRelation)\
and field.rel.to == inline_model\
and field.object_id_field_name == ct_fk_field\
and field.content_type_field_name == ct_field:
   inline_fields.append(field.name)
_autoregister(admin, inline_model)
else:
   fk_name = getattr(inline, 'fk_name', None)
if not fk_name:
   for field in inline_model._meta.fields:
   if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.rel.to):
   fk_name = field.name
_autoregister(admin, inline_model, follow = [fk_name])
if not inline_model._meta.get_field(fk_name).rel.is_hidden():
   accessor = inline_model._meta.get_field(fk_name).remote_field.get_accessor_name()
inline_fields.append(accessor)
_autoregister(admin, model, inline_fields)
def add_fields(self, form, index):
   ""
"Add a hidden field for the object's primary key."
""
from django.db.models
import AutoField, OneToOneField, ForeignKey
self._pk_field = pk = self.model._meta.pk
# If a pk isn 't editable, then it won'
t be on the form, so we need to
# add it here so we can tell which object is which when we get the
# data back.Generally, pk.editable should be false, but
for some
# reason, auto_created pk fields and AutoField 's editable attribute is
# True, so check
for that as well.

def pk_is_not_editable(pk):
   return ((not pk.editable) or(pk.auto_created or isinstance(pk, AutoField)) or(pk.rel and pk.rel.parent_link and pk_is_not_editable(pk.rel.to._meta.pk)))
if pk_is_not_editable(pk) or pk.name not in form.fields:
   if form.is_bound:
   # If we 're adding the related instance, ignore its primary key
# as it could be an auto - generated
default which isn 't actually
# in the database.
pk_value = None
if form.instance._state.adding
else form.instance.pk
else:
   try:
   if index is not None:
   pk_value = self.get_queryset()[index].pk
else:
   pk_value = None
except IndexError:
   pk_value = None
if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey):
   qs = pk.rel.to._default_manager.get_queryset()
else:
   qs = self.model._default_manager.get_queryset()
qs = qs.using(form.instance._state.db)
if form._meta.widgets:
   widget = form._meta.widgets.get(self._pk_field.name, HiddenInput)
else:
   widget = HiddenInput
form.fields[self._pk_field.name] = ModelChoiceField(qs, initial = pk_value, required = False, widget = widget)
super(BaseModelFormSet, self).add_fields(form, index)
def __init__(self, to, on_delete = models.DO_NOTHING, to_field = None, db_constraint = False, ** kwargs):
   super(OneToOneField, self).__init__(to, on_delete, to_field, db_constraint = db_constraint, ** kwargs)