How do you get a field related by OneToOneField and ManyToManyField in Django?

1.2k Views Asked by At

How do you get a field related by OneToOneField and ManyToManyField in Django?

For example,

class A(models.Model):
    myfield = models.CharField()
    as = models.ManyToManyField('self')
class B(models.Model):
    a = models.OneToOneField(A)

If I want to get a 'myfield' and all associated 'as' using class B, given a 'myfield' equal to a string like 'example', how is it done?

2

There are 2 best solutions below

0
On

Models.py

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

    def __str__(self):              # __unicode__ on Python 2
        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):              # __unicode__ on Python 2
        return "%s the restaurant" % self.place.name

Let create a place instance.

p1 = Place.objects.create(name='Demon Dogs', address='944 W. Fullerton')

Then create a restaurant object.

r = Restaurant.objects.create(place=p1, serves_hot_dogs=True, serves_pizza=False)

Now, to access place from Restaurant:

>>> r.place
 <Place: Demon Dogs the place>

vice-versa to access Restaurant from place

>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant>

I did not understand the many-to-many field part can you please elaborate?

0
On

First you get an instance of B say b and you can easily access myfield and as through the a attribute of b

b.a.myfield
b.a.as.all()

Furthermore, CharField requires a max_length attribute as follows:

class A(models.Model):
    myfield = models.CharField(max_length=128)
    as = models.ManyToManyField('self')
class B(models.Model):
    a = models.OneToOneField(A)

A general point, give more descriptive names to your models and their attributes, or at the very least, add comments explaining what these models represent