Multiple Django Table Inheritance and Model Creation

I have a code that follows an example for inheriting multiple tables, as indicated on the documentation page: http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance . I am trying to create a restaurant around the place.

I have already created a place, and I want to make the restaurant this way:

>>> p = Place.objects.get(id=12)
# If p is a Restaurant object, this will give the child class:
>>> p.restaurant
<Restaurant: ...>
>>> r = Restaurant(p)

but I just get this error:

TypeError: int() argument must be a string or a number, not 'Place'

I want to add more information to my models, so I don’t want to enter and manually set all fields equal. is there anyway to do this?

+3
source share
4 answers

, "", , . - Restaurant, Place. , Place._meta.get_fields_with_model() , . , GPLed, transifex.txcommon.models bcd274ce7815.

+3

, :

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

class Restaurant(models.Model):
    place = models.ForeignKey(Place)
    serves_hot_dogs = models.BooleanField()
    serves_pizza = models.BooleanField()

:

>>> p = Place.objects.get(id=12)
>>> r = Restaurant(place=p)
+1

. , :

, :

class RestaurantBase(models.Model):
    class Meta:
        abstract = True
    serves_hot_dogs = models.BooleanField(default=False)
    serves_pizza = models.BooleanField(default=False)

class Restaurant(Place, RestaurantBase):
    pass

class RestaurantStandalone(RestaurantBase):
    class Meta:
        managed = False
        db_table = Restaurant._meta.db_table
    place_ptr = models.OneToOneRelationship(Place)

, , , :

p = Places.objects.get(id=3)
r = RestaurantStandalone()
r.place_ptr = p
r.save()

-

r = Restaurant.objects.filter(place_ptr=p)
print(r.id)
>>3
+1
source

As I answered my own question here ,

I ended up doing something like

p = Place.objects.get(name="Bob Cafe")
Restaurant.objects.create(
    place_ptr = p.id,
    serves_hot_dogs = True,
    serves_pizza = False
)
0
source

Source: https://habr.com/ru/post/1753084/


All Articles